Fibonacci n-step number sequences: Difference between revisions
m
syntax highlighting fixup automation
No edit summary |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 63:
{{trans|Python: Callable class}}
<
Int addnum
[Int] memo
Line 87:
L(n, name) zip(2..10, ‘fibo tribo tetra penta hexa hepta octo nona deca’.split(‘ ’))
V fibber = Fiblike([1] [+] (0 .< n - 1).map(i -> Int(2 ^ i)))
print(‘n=#2, #5nacci -> #. ...’.format(n, name, (0.<15).map(i -> String(@fibber(i))).join(‘ ’)))</
{{out}}
Line 105:
=={{header|360 Assembly}}==
<
FIBONS CSECT
USING FIBONS,R13 base register
Line 192:
PG DS CL120 buffer
REGEQU
END FIBONS</
{{out}}
<pre>
Line 204:
=={{header|ACL2}}==
<
(if (endp xs)
0
Line 216:
(list (sum prevs)))))
(cons (first next)
(n-bonacci next (1- limit))))))</
Output:
Line 229:
=={{header|Action!}}==
<
PROC GenerateSeq(CARD ARRAY init BYTE nInit CARD ARRAY seq BYTE nSeq)
Line 303:
Test("nonanacci",fibInit,9,MAX)
Test("decanacci",fibInit,10,MAX)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Fibonacci_n-step_number_sequences.png Screenshot from Atari 8-bit computer]
Line 323:
First, we specify a package Bonacci, that defines the type Sequence (of Positive numbers), a function Generate that takes a given Start sequence and outputs a generalized N-Bonacci Sequence of a spefified Length, and some constant start sequences.
<
type Sequence is array(Positive range <>) of Positive;
Line 333:
Start_Tetranacci: constant Sequence := (1, 1, 2, 4);
Start_Lucas: constant Sequence := (2, 1);
end Bonacci;</
The implementation is quite straightforward.
<
function Generate(Start: Sequence; Length: Positive := 10) return Sequence is
Line 356:
end Generate;
end Bonacci;</
Finally, we actually generate some sequences, as required by the task. For convenience, we define a procedure Print that outputs a sequence,
<
procedure Test_Bonacci is
Line 380:
Print("Decanacci: ",
Bonacci.Generate((1, 1, 2, 4, 8, 16, 32, 64, 128, 256), 15));
end Test_Bonacci;</
The output:
Line 391:
=={{header|ALGOL 68}}==
<
# the initial values are taken from the init array #
PROC n step fibonacci sequence = ( []INT init, INT required count )[]INT:
Line 421:
print sequence( "tetrabonacci", n step fibonacci sequence( ( 1, 1, 2, 4 ), 10 ) );
print sequence( "lucus ", n step fibonacci sequence( ( 2, 1 ), 10 ) )
</syntaxhighlight>
{{out}}
<pre>
Line 432:
=={{header|APL}}==
{{works with|Dyalog APL}}
<
nacci ← 2*0⌈¯2+⍳
↑((⍳10)nStep¨⊂)¨(nacci¨2 3 4),⊂2 1</
{{out}}
<pre>1 1 2 3 5 8 13 21 34 55
Line 443:
=={{header|AppleScript}}==
===Functional===
<
use framework "Foundation"
use scripting additions
Line 687:
end tell
end zipWith
</syntaxhighlight>
{{Out}}
<pre>Lucas -> [2,1,3,4,7,11,18,29,47,76,123,199,322,521,843]
Line 702:
===Simple===
<
-- n: …nacci step size as integer. Alternatively "Lucas".
-- F: Maximum …nacci index required. (0-based.)
Line 745:
set AppleScript's text item delimiters to astid
return output</
{{output}}
<
tribonacci: 0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, 927, 1705, 3136 …
tetranacci: 0, 1, 1, 2, 4, 8, 15, 29, 56, 108, 208, 401, 773, 1490, 2872, 5536 …
Line 757:
nonanacci: 0, 1, 1, 2, 4, 8, 16, 32, 64, 128, 256, 511, 1021, 2040, 4076, 8144 …
decanacci: 0, 1, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1023, 2045, 4088, 8172 …
Lucas: 2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322, 521, 843, 1364 …"</
=={{header|AutoHotkey}}==
<
Loop, 9 {
Out .= seq "(" A_Index + 1 "): "
Line 776:
}
return, a
}</
'''Output:'''
<pre>nacci(2): 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610
Line 798:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
function sequence(values, howmany) {
init_length = length(values)
Line 829:
print("lucas :\t\t",sequence(a, 10))
}
</syntaxhighlight>
'''Output:'''
<pre>
Line 839:
=={{header|BASIC256}}==
<
# by Jjuanhdez, 06/2022
Line 889:
next j
next i
end subroutine</
{{out}}
<pre> fibonacci => 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, ...
Line 903:
=={{header|Batch File}}==
<
@echo off
Line 952:
endlocal
exit /b
</syntaxhighlight>
{{out}}
<pre>
Line 970:
=={{header|BBC BASIC}}==
The BBC BASIC '''SUM''' function is useful here.
<
PRINT "Fibonacci:"
Line 996:
NEXT
f%(i%-1) = s%
ENDPROC</
'''Output:'''
<pre>
Line 1,011:
=={{header|Befunge}}==
<
v9013"Tetranacci"9014"Lucas"<
>"iccanobirT"2109"iccanobiF"v
Line 1,018:
_$.1+:77+`^vg03:_0g+>\:1+#^
50p-\30v v\<>\30g1-\^$$_:1-
05g04\g< >`#^_:40p30g0>^!:g</
{{out}}
Line 1,030:
=={{header|Bracmat}}==
{{trans|PicoLisp}}
<
= Init Cnt N made tail
. ( plus
Line 1,070:
& out$(str$(pad$!name ": ") nacci$(!Init.12))
)
);</
Output:
<pre> fibonacci: 1 1 2 3 5 8 13 21 34 55 89 144
Line 1,084:
=={{header|BQN}}==
<
Nacci ← (2⋆0∾↕)∘(⊢-1˙)
>((↕10) NStep¨ <)¨ (Nacci¨ 2‿3‿4) ∾ <2‿1</
{{out}}
<pre>┌─
Line 1,097:
=={{header|C}}==
<
The function anynacci determines the n-arity of the sequence from the number of seed elements. 0 ended arrays are used since C does not have a way of determining the length of dynamic and function-passed integer arrays.*/
Line 1,139:
return 0;
}</
Output:
Line 1,158:
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
using System.Linq;
Line 1,241:
}
}
}</
<pre>Fibonacci 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,
Lucas 2, 1, 3, 4, 7, 11, 18, 29, 47, 76,
Line 1,248:
=={{header|C++}}==
<
#include <iostream>
#include <numeric>
Line 1,297:
}
return 0 ;
}</
Output:
<pre>fibonacci : 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
Line 1,322:
This version focuses on a clean, simple class that adapts to any pair of starting numbers and any order. Rather than summing over all history every time, it uses an O(1) incremental update to a running total. Thus, performance remains essentially unchanged even for very large orders.
<
#include <iostream>
#include <vector>
Line 1,388:
}
}
</syntaxhighlight>
=={{header|Clojure}}==
<
(letfn [(s [] (lazy-cat init (apply map + (map #(drop % (s)) (range (count init))))))]
(s)))
Line 1,399:
(show "Tribonacci" [1 1 2])
(show "Tetranacci" [1 1 2 4])
(show "Lucas" [2 1]))</
{{out}}
<pre>first 20 Fibonacci (1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765)
Line 1,407:
=={{header|CLU}}==
<
n_step = proc (seq: sequence[int], n: int) returns (int)
a: array[int] := sequence[int]$s2a(seq)
Line 1,453:
print_n(seq.seq, 10)
end
end start_up</
{{out}}
<pre>Fibonacci 1 1 2 3 5 8 13 21 34 55
Line 1,461:
=={{header|Common Lisp}}==
<
(defun gen-fib (lst m)
"Return the first m members of a generalized Fibonacci sequence using lst as initial values
Line 1,479:
(format t "Lucas series: ~a~%" (gen-fib '(2 1) 10))
(loop for i from 2 to 4
do (format t "Fibonacci ~a-step sequence: ~a~%" i (gen-fib (initial-values i) 10))))</
{{out}}
<pre>Lucas series: (2 1 3 4 7 11 18 29 47 76)
Line 1,488:
=={{header|D}}==
===Basic Memoization===
<
import std.stdio, std.algorithm, std.range, std.conv;
Line 1,516:
15.iota.map!fibber);
}
}</
{{out}}
<pre>[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Line 1,532:
===Callable Struct===
The output is similar.
<
struct fiblike(T) {
Line 1,566:
n, name, 15.iota.map!fib);
}
}</
===Struct With opApply===
The output is similar.
<
struct Fiblike(T) {
Line 1,613:
writefln("n=%2d, %5snacci -> %s", n, name, fib.takeApply(15));
}
}</
===Range Generator Version===
<
import std.stdio, std.algorithm, std.range, std.concurrency;
Line 1,634:
writefln("n=%2d, %5snacci -> %(%s, %), ...", n, name, fib.take(15));
}
}</
{{out}}
<pre>[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Line 1,650:
See [[#Pascal]].
=={{header|EchoLisp}}==
<
;; generate a recursive lambda() for a x-nacci
;; equip it with memoïzation
Line 1,674:
(make-nacci name seed)
(printf "%s[%d] → %d" name (vector-length seed) (take name 16))))
</syntaxhighlight>
{{out}}
Line 1,690:
=={{header|Elixir}}==
{{trans|Ruby}}
<
def anynacci(start_sequence, count) do
n = length(start_sequence)
Line 1,718:
:io.format("~11s: ", [name])
IO.inspect RC.anynacci(list, 15)
end)</
{{out}}
Line 1,735:
=={{header|Erlang}}==
<syntaxhighlight lang="text">
-module( fibonacci_nstep ).
Line 1,757:
{Sum_ns, _Not_sum_ns} = lists:split( Nth, Ns ),
{Nth, [lists:sum(Sum_ns) | Ns]}.
</syntaxhighlight>
{{out}}
<pre>
Line 1,768:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM FIBON
Line 1,812:
FIB("Lucas","2,1")
END PROGRAM
</syntaxhighlight>
=={{header|F_Sharp|F#}}==
<
let fiblike init =
Line 1,838:
(Seq.init prefix.Length (fun i -> (prefix.[i], i+2)))
printfn " lucas -> %A" (start (fiblike [2; 1]))
0</
Output
<pre>n= 2, fibonacci -> [1; 1; 2; 3; 5; 8; 13; 21; 34; 55; 89; 144; 233; 377; 610]
Line 1,853:
=={{header|Factor}}==
<code>building</code> is a dynamic variable that refers to the sequence being built by <code>make</code>. This is useful when the next element of the sequence depends on previous elements.
<
: n-bonacci ( n initial -- seq ) [
Line 1,862:
qw{ fibonacci tribonacci tetranacci lucas }
{ { 1 1 } { 1 1 2 } { 1 1 2 4 } { 2 1 } }
[ 10 swap n-bonacci "%-10s %[%3d, %]\n" printf ] 2each</
{{out}}
<pre>
Line 1,872:
=={{header|Forth}}==
<
: a{ here cell allot ;
: } , here over - cell / over ! ;
Line 1,896:
." tetranacci: " a{ 1 , 1 , 2 , 4 } show-nacci
." lucas: " a{ 2 , 1 } show-nacci
</syntaxhighlight>
{{out}}
<pre>fibonacci: 1 1 2 3 5 8 13 21 34 55
Line 1,905:
=={{header|Fortran}}==
<
! save this program as file f.f08
! gnu-linux command to build and test
Line 1,970:
end subroutine nacci
end program f
</syntaxhighlight>
<pre>
Line 2,012:
=={{header|FreeBASIC}}==
<
' Deduces the step, n, from the length of the dynamic array passed in
Line 2,062:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 2,073:
=={{header|FunL}}==
<
native scala.collection.mutable.Queue
Line 2,103:
t.row( ([k] + [seqs(i)(k) | i <- 0:4]).toIndexedSeq() )
print( t )</
{{out}}
Line 2,134:
=={{header|Go}}==
Solution using separate goroutines.
<
import "fmt"
Line 2,172:
fmt.Println()
}
}</
{{out}}
<pre>
Line 2,183:
=={{header|Groovy}}==
=====Solution=====
<
assert seed : "The seed list must be non-null and non-empty"
assert seed.every { it instanceof Number } : "Every member of the seed must be a number"
Line 2,196:
}
}
}</
=====Test=====
<
' fibonacci':[1,1],
'tribonacci':[1,1,2],
Line 2,214:
println " lucas[0]: ${fib([2,1],0)}"
println " tetra[3]: ${fib([1,1,2,4],3)}"</
{{out}}
<pre> fibonacci: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Line 2,230:
=={{header|Haskell}}==
<
import Control.Monad (zipWithM_)
Line 2,247:
zipWithM_ (\n name -> do putStr (name ++ "nacci -> ")
print $ take 15 $ nstep n)
[2..] (words "fibo tribo tetra penta hexa hepta octo nona deca")</
{{out}}
<pre>
Line 2,264:
Or alternatively, without imports – using only the default Prelude:
<
nStepFibonacci :: Int -> [Int]
Line 2,296:
justifyLeft :: Int -> Char -> String -> String
justifyLeft n c s = take n (s <> replicate n c)</
<pre>Lucas -> [2,1,3,4,7,11,18,29,47,76,123,199,322,521,843]
fibonaccci -> [1,1,2,3,5,8,13,21,34,55,89,144,233,377,610]
Line 2,310:
or in terms of '''unfoldr''':
{{Trans|Python}}
<
import Data.List (transpose, uncons, unfoldr)
Line 2,367:
justifyRight :: Int -> Char -> String -> String
justifyRight n c = (drop . length) <*> (replicate n c <>)</
{{Out}}
<pre>Recurrence relation sequences:
Line 2,385:
Works in both languages:
<
every writes("F2:\t"|right((fnsGen(1,1))\14,5) | "\n")
every writes("F3:\t"|right((fnsGen(1,1,2))\14,5) | "\n")
Line 2,399:
suspend cache[i]
}
end</
Output:
Line 2,414:
A slightly longer version of <tt>fnsGen</tt> that reduces the memory
footprint is:
<
every i := seq() do {
if i := (i > *cache, *cache) then {
Line 2,423:
suspend cache[i]
}
end</
The output is identical.
Line 2,429:
=={{header|J}}==
'''Solution''':<
'''Example''' ''(Lucas)'':<
2 1 3 4 7 11 18 29 47 76</
'''Example''' ''(extended 'nacci series)'':<
2 fibonacci 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
3 tribonacci 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
Line 2,454:
octonacci ✓
nonanacci ✓
decanacci ✓</
=={{header|Java}}==
Line 2,460:
'''Code:'''
<
{
public static int[] lucas(int n, int numRequested)
Line 2,504:
}
}
}</
Output:
Line 2,528:
=={{header|JavaScript}}==
===ES5===
<
return nacci(nacci([1,1], arity, arity), arity, len);
}
Line 2,553:
}
main();</
{{out}}
<pre>fib(2): 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610
Line 2,575:
===ES6===
<
'use strict';
Line 2,688:
// MAIN ---
return main();
})();</
<pre>Lucas -> [2,1,3,4,7,11,18,29,47,76,123,199,322,521,843]
fibonacci -> [1,1,2,3,5,8,13,21,34,55,89,144,233,377,610]
Line 2,702:
=={{header|jq}}==
{{Works with|jq|1.4}}
<
def nacci(arity; len):
arity as $arity | len as $len
Line 2,716:
def lucas(arity; len):
arity as $arity | len as $len
| [2,1] | nacci($arity; $arity) | nacci($arity; $len) ;</
'''Example''':
<
(range(2; 11) | "fib(\(.)): \(fib(.; 15))"),
(range(2; 11) | "lucas(\(.)): \(lucas(.; 15))")
;
main</
{{Out}}
$ jq -M -r -n -f fibonacci_n-step.jq
Line 2,734:
'''Generalized Fibonacci Iterator Definition'''
<syntaxhighlight lang="julia">
type NFib{T<:Integer}
n::T
Line 2,765:
return (f, fs)
end
</syntaxhighlight>
'''Specification of the n-step Fibonacci Iterator'''
The seeding for this series of sequences is <math>F_{1-n} = 1</math> and <math>F_{2-n} \ldots F_{0}=0</math>.
<syntaxhighlight lang="julia">
function fib_seeder{T<:Integer}(n::T)
a = zeros(BigInt, n)
Line 2,780:
NFib(n, k, fib_seeder)
end
</syntaxhighlight>
'''Specification of the Rosetta Code n-step Lucas Iterator'''
This iterator produces the task description's version of the Lucas Sequence ([https://oeis.org/A000032 OEIS A000032]) and its generalization to n-steps as was done by some of the other solutions to this task. The seeding for this series of sequences is <math>F_{1-n} = 3</math>, <math>F_{2-n} = -1</math> and, for <math>n > 2</math>, <math>F_{3-n} \ldots F_{0}=0</math>.
<syntaxhighlight lang="julia">
function luc_rc_seeder{T<:Integer}(n::T)
a = zeros(BigInt, n)
Line 2,796:
NFib(n, k, luc_rc_seeder)
end
</syntaxhighlight>
'''Specification of the MathWorld n-step Lucas Iterator'''
This iterator produces the Mathworld version of the Lucas Sequence ([http://mathworld.wolfram.com/LucasNumber.html Lucas Number] and [https://oeis.org/A000204 OEIS A000204]) and its generalization to n-steps according to Mathworld ([http://mathworld.wolfram.com/Lucasn-StepNumber.html Lucas n-Step Number] and [https://cs.uwaterloo.ca/journals/JIS/VOL8/Noe/noe5.html Primes in Fibonacci n-step and Lucas n-step Sequences]). The seeding for this series of sequences is <math>F_{0} = n</math> and <math>F_{1-n} \ldots F_{-1}=-1</math>.
<syntaxhighlight lang="julia">
function luc_seeder{T<:Integer}(n::T)
a = -ones(BigInt, n)
Line 2,811:
NFib(n, k, luc_seeder)
end
</syntaxhighlight>
'''Main'''
<syntaxhighlight lang="julia">
lo = 2
hi = 10
Line 2,850:
println()
end
</syntaxhighlight>
{{out}}
Line 2,889:
=={{header|Kotlin}}==
<
fun fibN(initial: IntArray, numTerms: Int) : IntArray {
Line 2,915:
println("%2d %-10s %s".format(i + 2, names[i], values))
}
}</
{{out}}
Line 2,933:
=={{header|Lua}}==
<
local iMax, sum = #seq - 1
while #seq < limit do
Line 2,952:
io.write(sequence.name .. ": ")
print(table.concat(nStepFibs(sequence.values, 10), " "))
end</
{{out}}
<pre>Fibonacci: 1 1 2 3 5 8 13 21 34 55
Line 2,960:
=={{header|Maple}}==
<
local n, i, values;
n := numelems(initValues);
Line 2,975:
printf ("nacci(%d): %a\n", i, convert(numSequence(initValues), list));
end do:
printf ("lucas: %a\n", convert(numSequence(Array([2, 1])), list));</
{{out}}
<pre>
Line 2,991:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">
f2=Function[{l,k},
Module[{n=Length@l,m},
Line 2,998:
Table[Last/@f2[{1,1}~Join~Table[0,{n-2}],15+n][[-18;;]],{n,2,10}]//TableForm
Table[Last/@f2[{1,2}~Join~Table[0,{n-2}],15+n][[-18;;]],{n,2,10}]//TableForm
</syntaxhighlight>
Output:
<pre>
Line 3,025:
=={{header|Nim}}==
{{trans|Python}}
<
proc fiblike(start: seq[int]): auto =
Line 3,051:
se.add(1 shl i)
let fibber = fiblike(se)
echo "n = ", align($n, 2), ", ", align(name, 5), "nacci -> ", toSeq(0..14).mapIt($fibber(it)).join(" "), " ..."</
Output:
<pre>@[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Line 3,068:
We will use lazy lists, so can get any amount of n-nacci numbers.
<
(define (n-fib-iterator ll)
(cons (car ll)
(lambda ()
(n-fib-iterator (append (cdr ll) (list (fold + 0 ll)))))))
</syntaxhighlight>
Testing:
<
(print "2, fibonacci : " (ltake (n-fib-iterator '(1 1)) 15))
(print "3, tribonacci: " (ltake (n-fib-iterator '(1 1 2)) 15))
Line 3,089:
5, pentanacci: (1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930)
2, lucas : (2 1 3 4 7 11 18 29 47 76 123 199 322 521 843)
</syntaxhighlight>
=={{header|PARI/GP}}==
Line 3,095:
Use genV if you prefer to supply a different starting vector.
<
genV(n)=v->for(i=3,min(#v,n),v[i]=2^(i-2));for(i=n+1,#v,v[i]=sum(j=i-n,i-1,v[j]));v
for(n=2,10,print(n"\t"gen(n)(10)))</
{{out}}
<pre>2 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Line 3,111:
=={{header|Pascal}}==
{{works with|Free_Pascal}}
<
type
Line 3,180:
write(sequence[k], ' ');
writeln;
end.</
Output:
<pre>% ./Fibbonacci
Line 3,201:
Fib(n)/Fib(n-1) tends to the golden ratio = 1.618... 1.618^100 > 2^64
{{works with|Free_Pascal}}
<
program FibbonacciN (output);
{$IFNDEF FPC}
Line 3,314:
write(NextNacci(Nacci),' ');
writeln;
END.</
=={{header|Perl}}==
<
use warnings;
use feature <say signatures>;
Line 3,332:
say $_-1 . ': ' . join ' ', (fib_n $_)[0..19] for 2..10;
say "\nLucas: " . join ' ', fib_n(2, [2,1], 20);</
{{out}}
<pre>1: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
Line 3,347:
=={{header|Phix}}==
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">nacci_noo</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">l</span><span style="color: #0000FF;">)</span>
Line 3,367:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%snacci: %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">names</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">f</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<pre>
Line 3,377:
=={{header|PHP}}==
<
/**
* @author Elad Yosifon
Line 3,458:
}
</syntaxhighlight>
{{out}}
<pre>
Line 3,474:
=={{header|PicoLisp}}==
<
(let N (length Init)
(make
(made Init)
(do (- Cnt N)
(link (apply + (tail N (made)))) ) ) ) )</
Test:
<
: (nacci (1 1) 10)
-> (1 1 2 3 5 8 13 21 34 55)
Line 3,499:
# Decanacci
: (nacci (1 1 2 4 8 16 32 64 128 256) 15)
-> (1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172)</
=={{header|PL/I}}==
<
n_step_Fibonacci: procedure options (main);
declare line character (100) varying;
Line 3,529:
end;
end;
end n_step_Fibonacci;</
Output:
<pre>
Line 3,549:
=={{header|Powershell}}==
<
Function Get-ExtendedFibonaciGenerator($InitialValues ){
$Values = $InitialValues
Line 3,566:
}.GetNewClosure()
}
</syntaxhighlight>
Example of invocation to generate up to decanaci
<
0..($Name.Length-1) | foreach { $Index = $_
$InitialValues = @(1) + @(foreach ($I In 0..$Index) { [Math]::Pow(2,$I) })
Line 3,580:
}
} | Format-Table -AutoSize
</syntaxhighlight>
Sample output
<pre>
Line 3,597:
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">
Procedure.i FibonacciLike(k,n=2,p.s="",d.s=".")
Line 3,654:
Debug ""
</syntaxhighlight>
'''Sample Output'''
Line 3,676:
=={{header|Python}}==
===Python: function returning a function===
<
addnum = len(start)
memo = start[:]
Line 3,708:
n= 9, nonanacci -> 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
n=10, decanacci -> 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
>>> </
===Python: Callable class===
<
def __init__(self, start):
self.addnum = len(start)
Line 3,744:
n= 9, nonanacci -> 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
n=10, decanacci -> 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
>>> </
===Python: Generator===
<
def fiblike(tail):
Line 3,765:
fib = fiblike([1] + [2 ** i for i in xrange(n - 1)])
items = list(islice(fib, 15))
print "n=%2i, %5snacci -> %s ..." % (n, name, items)</
{{out}}
<pre>[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Line 3,782:
Defining the Lucas series and the N-Step Fibonacci series in terms of unfoldr (dual to functools.reduce).
{{Works with|Python|3.7}}
<
from itertools import chain, count, islice
Line 3,907:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>Recurrence relation series:
Line 3,924:
=={{header|Quackery}}==
<
[ tuck size -
Line 3,946:
' [ fibonacci tribonacci tetranacci lucas ]
witheach
[ dup echo say ": " 10 swap do echo cr ]</
{{out}}
Line 3,957:
=={{header|Racket}}==
<
;; fib-list : [Listof Nat] x Nat -> [Listof Nat]
Line 3,981:
(cons 1 (build-list (sub1 n) (curry expt 2)))))
;; and with an initial (2 1)
(show-fibs "lucas" '(2 1))</
{{out}}
Line 3,999:
===Lazy List with Closure===
<syntaxhighlight lang="raku"
my @seq = |@start, { state $n = +@start; @seq[ ($n - $s .. $n++ - 1).grep: * >= 0 ].sum } … *;
}
Line 4,005:
put "{.fmt: '%2d'}-nacci: ", nacci($_)[^20] for 2..12 ;
put "Lucas: ", nacci(:start(2,1))[^20];</
{{out}}
<pre> 2-nacci: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
Line 4,023:
A slightly more straight forward way of constructing a lazy list.
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku"
flat gather {
take @xs[*];
Line 4,037:
say fib($n, [1])[^20];
}
say fib(2, [2,1])[^20];</
=={{header|REXX}}==
<
parse arg FibName values /*allows a Fibonacci name, starter vals*/
if FibName\='' then do; call nStepFib FibName,values; signal done; end
Line 4,074:
say right(Fname,11)'[sum'right(N,3) "terms]:" strip(L) '···'
return</
'''output''' when using the default input:
<pre>
Line 4,093:
=={{header|Ring}}==
<
# Project : Fibonacci n-step number sequences
Line 4,155:
next
see svect
</syntaxhighlight>
Output:
<pre>
Line 4,172:
=={{header|Ruby}}==
<
n = start_sequence.length # Get the n-step for the type of fibonacci sequence
result = start_sequence.dup # Create a new result array with the values copied from the array that was passed by reference
Line 4,192:
decanacci: [1,1,2,4,8,16,32,64,128,256] }
naccis.each {|name, seq| puts "%12s : %p" % [name, anynacci(seq, 15)]}</
{{out}}
<
fibonacci : [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
tribonacci : [1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, 927, 1705, 3136]
Line 4,204:
nonanacci : [1, 1, 2, 4, 8, 16, 32, 64, 128, 256, 511, 1021, 2040, 4076, 8144]
decanacci : [1, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1023, 2045, 4088, 8172]
</syntaxhighlight>
=={{header|Run BASIC}}==
<
a = fib("tribonacci ", "1,1,2")
a = fib("tetranacci ", "1,1,2,4")
Line 4,228:
next i
print
end function</
{{out}}
<pre> fibonacci => 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377,
Line 4,238:
=={{header|Rust}}==
<
struct GenFibonacci {
buf: Vec<u64>,
Line 4,280:
print(vec![2,1], 10 - 2);
}
</syntaxhighlight>
<syntaxhighlight lang="text">
Fib2: 1 1 2 3 5 8 13 21 34 55
Fib3: 1 1 2 4 7 13 24 44 81 149
Fib4: 1 1 2 4 8 15 29 56 108 208
Lucas: 2 1 3 4 7 11 18 29 47 76
</syntaxhighlight>
=={{header|Scala}}==
===Simple Solution===
<
//we rely on implicit conversion from Int to BigInt.
//BigInt is preferable since the numbers get very big, very fast.
Line 4,300:
inner(init.toVector)
}
</syntaxhighlight>
===Optimizing===
<
//in the optimized version we don't compute values until it's needed.
//the unoptimized version, computed k elements ahead, where k being
Line 4,315:
init.to(LazyList) #::: inner(init.toVector)
}
</syntaxhighlight>
===Optimizing Further===
<
//instead of summing k elements each phase, we exploit the fact
//that the last element is already the sum of all k preceding elements
Line 4,330:
v.to(LazyList) #::: inner(v)
}
</syntaxhighlight>
===Printing===
<
println(s"Fibonacci: ${fibStream(1,1).take(10).mkString(",")}")
println(s"Tribonacci: ${fibStream(1,1,2).take(10).mkString(",")}")
println(s"Tetranacci: ${fibStream(1,1,2,4).take(10).mkString(",")}")
println(s"Lucas: ${fibStream(2,1).take(10).mkString(",")}")
</syntaxhighlight>
{{out}}
<pre>
Line 4,349:
=={{header|Scheme}}==
<
(import (scheme base)
(scheme write)
Line 4,376:
(display (n-fib '(2 1) 15))
(newline)
</syntaxhighlight>
{{out}}
Line 4,387:
=={{header|Seed7}}==
<
const func array integer: bonacci (in array integer: start, in integer: arity, in integer: length) is func
Line 4,423:
print("Tetranacci", bonacci([] (1, 1), 4, 10));
print("Lucas", bonacci([] (2, 1), 2, 10));
end func;</
{{out}}
Line 4,435:
=={{header|Sidef}}==
{{trans|Perl}}
<
loop {
var len = xs.len
Line 4,447:
say fib(i).join(' ')
}
say fib(2, [2, 1]).join(' ')</
{{out}}
<pre>
Line 4,463:
Using matrix exponentiation:
<
Matrix.build(k,k, {|i,j|
((i == k-1) || (i == j-1)) ? 1 : 0
Line 4,476:
for k in (2..9) {
say ("Fibonacci of k=#{k} order: ", (15+k).of { fibonacci_kth_order(_, k) })
}</
{{out}}
<pre>
Line 4,490:
Faster algorithm:
<
return 0 if (n < k-1)
Line 4,509:
for k in (2..9) {
say ("Fibonacci of k=#{k} order: ", (15+k).of { fibonacci_kth_order(_, k) })
}</
(same output as above)
=={{header|Tailspin}}==
<
templates fibonacciNstep&{N:}
templates next
Line 4,543:
'
' -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
Line 4,554:
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<
proc fibber {args} {
Line 4,583:
print10 [fibber 1 1 2 4]
puts "LUCAS"
print10 [fibber 2 1]</
{{out}}
<pre>
Line 4,597:
=={{header|VBA}}==
<
Sub Main()
Line 4,658:
Next
Fibonacci_Step = R
End Function</
{{Out}}
Line 4,667:
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
'function arguments:
'init - initial series of the sequence(e.g. "1,1")
Line 4,699:
WScript.StdOut.Write "lucas: " & generate_seq("2,1",15)
WScript.StdOut.WriteLine
</syntaxhighlight>
{{Out}}
Line 4,712:
{{trans|Visual Basic}}
{{works with|Visual Basic .NET|2011}}
<
Public Class FibonacciNstep
Line 4,749:
End Function 'FibonacciN
End Class 'FibonacciNstep</
{{out}}
<pre>
Line 4,762:
=={{header|Vlang}}==
{{trans|Wren}}
<
n := initial.len
if n < 2 || num_terms < 0 {panic("Invalid argument(s).")}
Line 4,795:
println(values.map('${it:4}').join(' '))
}
}</
{{out}}
Line 4,815:
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<
var fibN = Fn.new { |initial, numTerms|
Line 4,844:
Fmt.write("$2d $-10s", i + 2, names[i])
Fmt.aprint(values, 4, 0, "")
}</
{{out}}
Line 4,862:
=={{header|XPL0}}==
<
proc Nacci(N, F0); \Generate Fibonacci N-step sequence
Line 4,884:
Text(0, "Tetranacci: "); Nacci(4, [1, 1, 2, 4]);
Text(0, " Lucas: "); Nacci(2, [2, 1]);
]</
Output:
Line 4,896:
=={{header|Yabasic}}==
{{trans|Lua}}
<
local iMax, sum, numb$(1), lim, i
Line 4,916:
print "Tribonacci:", nStepFibs$("1,1,2", 10)
print "Tetranacci:", nStepFibs$("1,1,2,4", 10)
print "Lucas:", nStepFibs$("2,1", 10)</
=={{header|zkl}}==
<
This stores the initial n terms of the sequence and returns a function that, at each call, appends the sum of the terms to the sequence then pops the leading value and returns it.
<
lucas:=fibN(2,1); do(N){ lucas().print(","); } println(); // Lucas
ns:=L(1); foreach _ in ([ns.len()+1..10]){ // Fibonacci n-step for 2 .. 10
Line 4,927:
"%2d: ".fmt(ns.len()).print();
(N).pump(List,fibN(ns.xplode())).println();
}</
{{out}}
<pre>
|