Fibonacci n-step number sequences: Difference between revisions

Added various BASIC dialects (Chipmunk Basic, QBasic, and QB64)
(Added Maple implementation.)
(Added various BASIC dialects (Chipmunk Basic, QBasic, and QB64))
 
(119 intermediate revisions by 40 users not shown)
Line 8:
For small values of <math>n</math>, [[wp:Number prefix#Greek_series|Greek numeric prefixes]] are sometimes used to individually name each series.
 
:::: {| style="text-align: left;" border="4" cellpadding="2" cellspacing="2"
|+ Fibonacci <math>n</math>-step sequences
|- style="background-color: rgb(255, 204, 255);"
Line 33:
 
Allied sequences can be generated where the initial values are changed:
: '''The [[wp:Lucas number|Lucas series]]''' sums the two preceedingpreceding values like the fibonacci series for <math>n=2</math> but uses <math>[2, 1]</math> as its initial values.
 
<!-- Lucas numbers, Lucas number, Lucas series [added to make searches easier.] -->
;The task is to:
 
<br>
;Task:
# Write a function to generate Fibonacci <math>n</math>-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
# Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.
 
 
;Cf.:
;Related tasks:
* [[Fibonacci sequence]]
* &nbsp; [[Fibonacci sequence]]
* [http://mathworld.wolfram.com/Fibonaccin-StepNumber.html Wolfram Mathworld]
* &nbsp; [http://mathworld.wolfram.com/Fibonaccin-StepNumber.html Wolfram Mathworld]
* [[Hofstadter Q sequence‎]]
* &nbsp; [[Hofstadter Q sequence‎]]
* [https://www.youtube.com/watch?v=PeUbRXnbmms Lucas Numbers - Numberphile] (Video).
* &nbsp; [[Leonardo numbers]]
 
 
;Also see:
* &nbsp; [https://www.youtube.com/watch?v=PeUbRXnbmms Lucas Numbers - Numberphile] (Video)
* &nbsp; [https://www.youtube.com/watch?v=fMJflV_GUpU Tribonacci Numbers (and the Rauzy Fractal) - Numberphile] (Video)
* &nbsp; [[wp:Lucas number|Wikipedia, Lucas number]]
* &nbsp; [http://mathworld.wolfram.com/FibonacciNumber.html MathWorld, Fibonacci Number]
* &nbsp; [http://www.math-cs.ucmo.edu/~curtisc/articles/howardcooper/genfib4.pdf Some identities for r-Fibonacci numbers]
* &nbsp; [[oeis:A000045|OEIS Fibonacci numbers]]
* &nbsp; [[oeis:A000032|OEIS Lucas numbers]]
<br><br>
 
=={{header|11l}}==
{{trans|Python: Callable class}}
 
<syntaxhighlight lang="11l">T Fiblike
Int addnum
[Int] memo
 
F (start)
.addnum = start.len
.memo = copy(start)
 
F ()(n)
X.try
R .memo[n]
X.catch IndexError
V ans = sum((n - .addnum .< n).map(i -> (.)(i)))
.memo.append(ans)
R ans
 
V fibo = Fiblike([1, 1])
print((0.<10).map(i -> fibo(i)))
 
V lucas = Fiblike([2, 1])
print((0.<10).map(i -> lucas(i)))
 
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(‘ ’)))</syntaxhighlight>
 
{{out}}
<pre>
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
[2, 1, 3, 4, 7, 11, 18, 29, 47, 76]
n= 2, fibonacci -> 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
n= 3, tribonacci -> 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
n= 4, tetranacci -> 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
n= 5, pentanacci -> 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
n= 6, hexanacci -> 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
n= 7, heptanacci -> 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
n= 8, octonacci -> 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
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 ...
</pre>
 
=={{header|360 Assembly}}==
<syntaxhighlight lang="360asm">* Fibonacci n-step number sequences - 14/04/2020
FIBONS CSECT
USING FIBONS,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R6,2 i=2
DO WHILE=(C,R6,LE,=F'7') do i=2 to 7
ST R6,IR ir=i
IF C,R6,EQ,=F'7' THEN if i=7 then - Lucas
LA R0,2 2
ST R0,IR ir=2
ENDIF , endif
LA R0,1 1
ST R0,T t(1)=1
IF C,R6,EQ,=F'7' THEN if i=7 then - Lucas
LA R0,2 2
ST R0,T t(1)=2
ENDIF , endif
LA R0,1 1
ST R0,T+4 t(2)=1
LA R7,3 j=3
DO WHILE=(C,R7,LE,=A(NMAX)) do j=3 to nmax
SR R0,R0 0
ST R0,SUM sum=0
LR R11,R7 j
S R11,IR j-ir
LR R8,R7 k=j
BCTR R8,0 k=j-1
DO WHILE=(CR,R8,GE,R11) do k=j-1 to j-ir by -1
IF LTR,R8,P,R8 THEN if k>0 then
LR R1,R8 k
SLA R1,2 ~
L R2,T-4(R1) t(k)
L R1,SUM sum
AR R1,R2 +
ST R1,SUM sum=sum+t(k)
ENDIF , endif
BCTR R8,0 k--
ENDDO , enddo k
L R0,SUM sum
LR R1,R7 j
SLA R1,2 ~
ST R0,T-4(R1) t(j)=sum
LA R7,1(R7) j++
ENDDO , enddo j
MVC PG,=CL120' ' clear buffer
LA R9,PG @buffer
LR R1,R6 i
BCTR R1,0 i-1
MH R1,=H'5' ~
LA R4,BONACCI-5(R1) @bonacci(i-1)
MVC 0(5,R9),0(R4) output bonacci(i-1)
LA R9,5(R9) @buffer
IF C,R6,NE,=F'7' THEN if i<>7 then
MVC 0(7,R9),=C'nacci: ' output 'nacci: '
ELSE , else
MVC 0(7,R9),=C' : ' output ' : '
ENDIF , endif
LA R9,7(R9) @buffer
LA R7,1 j=1
DO WHILE=(C,R7,LE,=A(NMAX)) do j=1 to nmax
LR R1,R7 j
SLA R1,2 ~
L R2,T-4(R1) t(j)
XDECO R2,XDEC edit t(j)
MVC 0(6,R9),XDEC+6 output t(j)
LA R9,6(R9) @buffer
LA R7,1(R7) j++
ENDDO , enddo j
XPRNT PG,L'PG print buffer
LA R6,1(R6) i++
ENDDO , enddo i
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling sav
NMAX EQU 18 sequence length
BONACCI DC CL5' fibo',CL5'tribo',CL5'tetra',CL5'penta',CL5' hexa'
DC CL5'lucas' bonacci(6)
IR DS F ir
SUM DS F sum
T DS (NMAX)F t(nmax)
XDEC DS CL12 temp for xdeco
PG DS CL120 buffer
REGEQU
END FIBONS</syntaxhighlight>
{{out}}
<pre>
fibonacci: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584
tribonacci: 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 5768 10609 19513
tetranacci: 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 10671 20569 39648
pentanacci: 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 13624 26784 52656
hexanacci: 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 15109 29970 59448
lucas : 2 1 3 4 7 11 18 29 47 76 123 199 322 521 843 1364 2207 3571
</pre>
 
=={{header|ACL2}}==
<syntaxhighlight lang="lisp">(defun sum (xs)
(if (endp xs)
0
(+ (first xs)
(sum (rest xs)))))
 
(defun n-bonacci (prevs limit)
(if (zp limit)
nil
(let ((next (append (rest prevs)
(list (sum prevs)))))
(cons (first next)
(n-bonacci next (1- limit))))))</syntaxhighlight>
 
Output:
<pre>&gt; (n-bonacci '(1 1) 10)
(1 2 3 5 8 13 21 34 55 89)
&gt; (n-bonacci '(1 1 2) 10)
(1 2 4 7 13 24 44 81 149 274)
&gt; (n-bonacci '(1 1 2 4) 10)
(1 2 4 8 15 29 56 108 208 401)
&gt; (n-bonacci '(2 1) 10)
(1 3 4 7 11 18 29 47 76 123)</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">DEFINE MAX="15"
 
PROC GenerateSeq(CARD ARRAY init BYTE nInit CARD ARRAY seq BYTE nSeq)
CARD next
BYTE i,j,n
 
IF nInit<nSeq THEN
n=nInit
ELSE
n=nSeq
FI
 
FOR i=0 TO n-1
DO
seq(i)=init(i)
OD
 
FOR i=n TO nSeq-1
DO
next=0
FOR j=i-nInit TO i-1
DO
next==+seq(j)
OD
seq(i)=next
OD
RETURN
 
PROC PrintSeq(CHAR ARRAY name CARD ARRAY seq BYTE n)
BYTE i
 
PrintF("%S=[",name)
FOR i=0 TO n-1
DO
PrintC(seq(i))
IF i<n-1 THEN
Print(" ")
ELSE
PrintE("]")
FI
OD
RETURN
 
PROC SetInverseVideo(CHAR ARRAY text)
BYTE i
 
FOR i=1 TO text(0)
DO
text(i)=text(i) OR $80
OD
RETURN
 
PROC Test(CHAR ARRAY name CARD ARRAY init CARD ARRAY nInit BYTE nSeq)
CARD ARRAY seq(MAX)
 
SetInverseVideo(name)
GenerateSeq(init,nInit,seq,nSeq)
PrintSeq(name,seq,nSeq)
RETURN
 
PROC Main()
CARD ARRAY fibInit=[1 1 2 4 8 16 32 64 128 256 512]
CARD ARRAY lucInit=[2 1]
 
Test("lucas",lucInit,2,MAX)
Test("fibonacci",fibInit,2,MAX)
Test("tribonacci",fibInit,3,MAX)
Test("tetranacci",fibInit,4,MAX)
Test("pentanacci",fibInit,5,MAX)
Test("hexanacci",fibInit,6,MAX)
Test("heptanacci",fibInit,7,MAX)
Test("octanacci",fibInit,8,MAX)
Test("nonanacci",fibInit,9,MAX)
Test("decanacci",fibInit,10,MAX)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Fibonacci_n-step_number_sequences.png Screenshot from Atari 8-bit computer]
<pre>
lucas=[2 1 3 4 7 11 18 29 47 76 123 19 9 322 521 843]
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]
tetranacci=[1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536]
pentanacci=[1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930]
hexanacci=[1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617]
heptanacci=[1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936]
octanacci=[1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080]
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]
</pre>
 
=={{header|Ada}}==
Line 49 ⟶ 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.
 
<langsyntaxhighlight Adalang="ada">package Bonacci is
 
type Sequence is array(Positive range <>) of Positive;
Line 59 ⟶ 333:
Start_Tetranacci: constant Sequence := (1, 1, 2, 4);
Start_Lucas: constant Sequence := (2, 1);
end Bonacci;</langsyntaxhighlight>
 
The implementation is quite straightforward.
 
<langsyntaxhighlight Adalang="ada">package body Bonacci is
 
function Generate(Start: Sequence; Length: Positive := 10) return Sequence is
Line 82 ⟶ 356:
end Generate;
 
end Bonacci;</langsyntaxhighlight>
 
Finally, we actually generate some sequences, as required by the task. For convenience, we define a procedure Print that outputs a sequence,
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Bonacci;
 
procedure Test_Bonacci is
Line 106 ⟶ 380:
Print("Decanacci: ",
Bonacci.Generate((1, 1, 2, 4, 8, 16, 32, 64, 128, 256), 15));
end Test_Bonacci;</langsyntaxhighlight>
 
The output:
Line 115 ⟶ 389:
Lucas: ( 2, 1, 3, 4, 7, 11, 18, 29, 47, 76 )
Decanacci: ( 1, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1023, 2045, 4088, 8172 )</pre>
 
=={{header|ACL2}}==
<lang lisp>(defun sum (xs)
(if (endp xs)
0
(+ (first xs)
(sum (rest xs)))))
 
(defun n-bonacci (prevs limit)
(if (zp limit)
nil
(let ((next (append (rest prevs)
(list (sum prevs)))))
(cons (first next)
(n-bonacci next (1- limit))))))</lang>
 
Output:
<pre>&gt; (n-bonacci '(1 1) 10)
(1 2 3 5 8 13 21 34 55 89)
&gt; (n-bonacci '(1 1 2) 10)
(1 2 4 7 13 24 44 81 149 274)
&gt; (n-bonacci '(1 1 2 4) 10)
(1 2 4 8 15 29 56 108 208 401)
&gt; (n-bonacci '(2 1) 10)
(1 3 4 7 11 18 29 47 76 123)</pre>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68"># returns an array of the first required count elements of an a n-step fibonacci sequence #
# the initial values are taken from the init array #
PROC n step fibonacci sequence = ( []INT init, INT required count )[]INT:
Line 172 ⟶ 421:
print sequence( "tetrabonacci", n step fibonacci sequence( ( 1, 1, 2, 4 ), 10 ) );
print sequence( "lucus ", n step fibonacci sequence( ( 2, 1 ), 10 ) )
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 180 ⟶ 429:
lucus : 2 1 3 4 7 11 18 29 47 76
</pre>
 
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">nStep ← {⊃(1↓⊢,+/)⍣(⍺-1)⊢⍵}
nacci ← 2*0⌈¯2+⍳
↑((⍳10)nStep¨⊂)¨(nacci¨2 3 4),⊂2 1</syntaxhighlight>
{{out}}
<pre>1 1 2 3 5 8 13 21 34 55
1 1 2 4 7 13 24 44 81 149
1 1 2 4 8 15 29 56 108 208
2 1 3 4 7 11 18 29 47 76</pre>
 
=={{header|AppleScript}}==
===Functional===
<syntaxhighlight lang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
 
 
-- Start sequence -> Number of terms -> terms
-- takeNFibs :: [Int] -> Int -> [Int]
on takeNFibs(xs, n)
script go
on |λ|(xs, n)
if 0 < n and 0 < length of xs then
cons(head(xs), ¬
|λ|(append(tail(xs), {sum(xs)}), n - 1))
else
{}
end if
end |λ|
end script
go's |λ|(xs, n)
end takeNFibs
 
-- fibInit :: Int -> [Int]
on fibInit(n)
script powerOfTwo
on |λ|(x)
2 ^ x as integer
end |λ|
end script
cons(1, map(powerOfTwo, enumFromToInt(0, n - 2)))
end fibInit
 
-- TEST ---------------------------------------------------
on run
set intTerms to 15
script series
on |λ|(s, n)
justifyLeft(12, space, s & "nacci") & " -> " & ¬
showJSON(takeNFibs(fibInit(n), intTerms))
end |λ|
end script
set strTable to unlines(zipWith(series, ¬
words of ("fibo tribo tetra penta hexa hepta octo nona deca"), ¬
enumFromToInt(2, 10)))
justifyLeft(12, space, "Lucas ") & " -> " & ¬
showJSON(takeNFibs({2, 1}, intTerms)) & linefeed & strTable
end run
 
-- GENERIC FUNCTIONS --------------------------------------
 
-- Append two lists.
-- append (++) :: [a] -> [a] -> [a]
-- append (++) :: String -> String -> String
on append(xs, ys)
xs & ys
end append
 
-- cons :: a -> [a] -> [a]
on cons(x, xs)
if list is class of xs then
{x} & xs
else
x & xs
end if
end cons
 
-- enumFromToInt :: Int -> Int -> [Int]
on enumFromToInt(m, n)
if m ≤ n then
set lst to {}
repeat with i from m to n
set end of lst to i
end repeat
return lst
else
return {}
end if
end enumFromToInt
 
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
 
-- head :: [a] -> a
on head(xs)
if xs = {} then
missing value
else
item 1 of xs
end if
end head
 
-- justifyLeft :: Int -> Char -> String -> String
on justifyLeft(n, cFiller, strText)
if n > length of strText then
text 1 thru n of (strText & replicate(n, cFiller))
else
strText
end if
end justifyLeft
 
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
 
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
 
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
 
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if n < 1 then return out
set dbl to {a}
repeat while (n > 1)
if (n mod 2) > 0 then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
 
-- showJSON :: a -> String
on showJSON(x)
set c to class of x
if (c is list) or (c is record) then
set ca to current application
set {json, e} to ca's NSJSONSerialization's ¬
dataWithJSONObject:x options:0 |error|:(reference)
if json is missing value then
e's localizedDescription() as text
else
(ca's NSString's alloc()'s ¬
initWithData:json encoding:(ca's NSUTF8StringEncoding)) as text
end if
else if c is date then
"\"" & ((x - (time to GMT)) as «class isot» as string) & ".000Z" & "\""
else if c is text then
"\"" & x & "\""
else if (c is integer or c is real) then
x as text
else if c is class then
"null"
else
try
x as text
on error
("«" & c as text) & "»"
end try
end if
end showJSON
 
-- sum :: [Num] -> Num
on sum(xs)
script add
on |λ|(a, b)
a + b
end |λ|
end script
foldl(add, 0, xs)
end sum
 
-- tail :: [a] -> [a]
on tail(xs)
set blnText to text is class of xs
if blnText then
set unit to ""
else
set unit to {}
end if
set lng to length of xs
if 1 > lng then
missing value
else if 2 > lng then
unit
else
if blnText then
text 2 thru -1 of xs
else
rest of xs
end if
end if
end tail
 
-- unlines :: [String] -> String
on unlines(xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set str to xs as text
set my text item delimiters to dlm
str
end unlines
 
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(length of xs, length of ys)
if 1 > lng then return {}
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, item i of ys)
end repeat
return lst
end tell
end zipWith
</syntaxhighlight>
{{Out}}
<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]
tribonacci -> [1,1,2,4,7,13,24,44,81,149,274,504,927,1705,3136]
tetranacci -> [1,1,2,4,8,15,29,56,108,208,401,773,1490,2872,5536]
pentanacci -> [1,1,2,4,8,16,31,61,120,236,464,912,1793,3525,6930]
hexanacci -> [1,1,2,4,8,16,32,63,125,248,492,976,1936,3840,7617]
heptanacci -> [1,1,2,4,8,16,32,64,127,253,504,1004,2000,3984,7936]
octonacci -> [1,1,2,4,8,16,32,64,128,255,509,1016,2028,4048,8080]
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]</pre>
 
===Simple===
 
<syntaxhighlight lang="applescript">-- Parameters:
-- n: …nacci step size as integer. Alternatively "Lucas".
-- F: Maximum …nacci index required. (0-based.)
on fibonacciNStep(n, F)
script o
property sequence : {0}
end script
if (n is "Lucas") then set {n, item 1 of o's sequence} to {2, 2}
-- F1 (if included) is always 1.
if (F > 0) then set end of o's sequence to 1
-- F2 (ditto) is F0 + F1.
if (F > 1) then set end of o's sequence to (beginning of o's sequence) + (end of o's sequence)
-- Each further number up to and including Fn is twice the number preceding it.
if (n > F) then set n to F
repeat (n - 2) times
set end of o's sequence to (end of o's sequence) * 2
end repeat
-- Beyond Fn, each number is twice the one preceding it, minus the number n places before that.
set nBeforeEnd to -(n + 1)
repeat (F - n) times
set end of o's sequence to (end of o's sequence) * 2 - (item nBeforeEnd of o's sequence)
end repeat
return o's sequence
end fibonacciNStep
 
-- Test code:
set maxF to 15 -- Length of sequence required after the initial 0 or 2.
set seriesNames to {missing value, "fibonacci: ", "tribonacci: ", "tetranacci: ", "pentanacci: ", ¬
"hexanacci: ", "heptanacci: ", "octonacci: ", "nonanacci: ", "decanacci: "}
set output to {}
 
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ", "
repeat with nacciSize from 2 to 10
set end of output to (item nacciSize of seriesNames) & fibonacciNStep(nacciSize, maxF) & " …"
end repeat
set end of output to "Lucas: " & fibonacciNStep("lucas", maxF) & " …"
set AppleScript's text item delimiters to linefeed
set output to output as text
set AppleScript's text item delimiters to astid
 
return output</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">"fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610 …
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 …
pentanacci: 0, 1, 1, 2, 4, 8, 16, 31, 61, 120, 236, 464, 912, 1793, 3525, 6930 …
hexanacci: 0, 1, 1, 2, 4, 8, 16, 32, 63, 125, 248, 492, 976, 1936, 3840, 7617 …
heptanacci: 0, 1, 1, 2, 4, 8, 16, 32, 64, 127, 253, 504, 1004, 2000, 3984, 7936 …
octonacci: 0, 1, 1, 2, 4, 8, 16, 32, 64, 128, 255, 509, 1016, 2028, 4048, 8080 …
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 …"</syntaxhighlight>
 
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">naccis: #[
lucas: [2 1]
fibonacci: [1 1]
tribonacci: [1 1 2]
tetranacci: [1 1 2 4]
pentanacci: [1 1 2 4 8]
hexanacci: [1 1 2 4 8 16]
heptanacci: [1 1 2 4 8 16 32]
octonacci: [1 1 2 4 8 16 32 64]
nonanacci: [1 1 2 4 8 16 32 64 128]
decanacci: [1 1 2 4 8 16 32 64 128 256]
]
 
anyNacci: function [start, count][
n: size start
result: new start
do.times: count-n ->
result: result ++ sum last.n:n result
 
return join.with:", " to [:string] result
]
 
loop naccis [k,v][
print [pad (k ++ ":") 12 anyNacci v 15]
]</syntaxhighlight>
 
{{out}}
 
<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
tribonacci: 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, 927, 1705, 3136
tetranacci: 1, 1, 2, 4, 8, 15, 29, 56, 108, 208, 401, 773, 1490, 2872, 5536
pentanacci: 1, 1, 2, 4, 8, 16, 31, 61, 120, 236, 464, 912, 1793, 3525, 6930
hexanacci: 1, 1, 2, 4, 8, 16, 32, 63, 125, 248, 492, 976, 1936, 3840, 7617
heptanacci: 1, 1, 2, 4, 8, 16, 32, 64, 127, 253, 504, 1004, 2000, 3984, 7936
octonacci: 1, 1, 2, 4, 8, 16, 32, 64, 128, 255, 509, 1016, 2028, 4048, 8080
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</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">for i, seq in ["nacci", "lucas"]
Loop, 9 {
Out .= seq "(" A_Index + 1 "): "
Line 198 ⟶ 816:
}
return, a
}</langsyntaxhighlight>
'''Output:'''
<pre>nacci(2): 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610
Line 218 ⟶ 836:
lucas(9): 2, 1, 3, 6, 12, 24, 48, 96, 192, 384, 766, 1531, 3059, 6112, 12212
lucas(10): 2, 1, 3, 6, 12, 24, 48, 96, 192, 384, 768, 1534, 3067, 6131, 12256</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
function sequence(values, howmany) {
init_length = length(values)
for (i=init_length + 1; i<=howmany; i++) {
values[i] = 0
for (j=1; j<=init_length; j++) {
values[i] += values[i-j]
}
}
result = ""
for (i in values) {
result = result values[i] " "
}
delete values
return result
}
 
# print some sequences
END {
a[1] = 1; a[2] = 1
print("fibonacci :\t",sequence(a, 10))
 
a[1] = 1; a[2] = 1; a[3] = 2
print("tribonacci :\t",sequence(a, 10))
 
a[1] = 1 ; a[2] = 1 ; a[3] = 2 ; a[4] = 4
print("tetrabonacci :\t",sequence(a, 10))
 
a[1] = 2; a[2] = 1
print("lucas :\t\t",sequence(a, 10))
}
</syntaxhighlight>
'''Output:'''
<pre>
fibonacci : 1 1 2 3 5 8 13 21 34 55
tribonacci : 1 1 2 4 7 13 24 44 81 149
tetrabonacci : 1 1 2 4 8 15 29 56 108 208
lucas : 2 1 3 4 7 11 18 29 47 76
</pre>
 
=={{header|BASIC}}==
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256"># Rosetta Code problem: https://www.rosettacode.org/wiki/Fibonacci_n-step_number_sequences
# by Jjuanhdez, 06/2022
 
arraybase 1
print " fibonacci =>";
dim a = {1,1}
call fib (a)
print " tribonacci =>";
dim a = {1,1,2}
call fib (a)
print " tetranacci =>";
dim a = {1,1,2,4}
call fib (a)
print " pentanacci =>";
dim a = {1,1,2,4,8}
call fib (a)
print " hexanacci =>";
dim a = {1,1,2,4,8,16}
call fib (a)
print " heptanacci =>";
dim a = {1,1,2,4,8,16,32}
call fib (a)
print " octonacci =>";
dim a = {1,1,2,4,8,16,32,64}
call fib (a)
print " nonanacci =>";
dim a = {1,1,2,4,8,16,32,64,128}
call fib (a)
print " decanacci =>";
dim a = {1,1,2,4,8,16,32,64,128,256}
call fib (a)
print " lucas =>";
dim a = {2,1}
call fib (a)
end
 
subroutine fib (a)
dim f(24) fill 0
b = 0
for x = 1 to a[?]
b += 1
f[x] = a[x]
next x
for i = b to 13 + b
print rjust(f[i-b+1], 5);
if i <> 13 + b then print ","; else print ", ..."
for j = (i-b+1) to i
f[i+1] = f[i+1] + f[j]
next j
next i
end subroutine</syntaxhighlight>
{{out}}
<pre> fibonacci => 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, ...
tribonacci => 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, 927, 1705, ...
tetranacci => 1, 1, 2, 4, 8, 15, 29, 56, 108, 208, 401, 773, 1490, 2872, ...
pentanacci => 1, 1, 2, 4, 8, 16, 31, 61, 120, 236, 464, 912, 1793, 3525, ...
hexanacci => 1, 1, 2, 4, 8, 16, 32, 63, 125, 248, 492, 976, 1936, 3840, ...
heptanacci => 1, 1, 2, 4, 8, 16, 32, 64, 127, 253, 504, 1004, 2000, 3984, ...
octonacci => 1, 1, 2, 4, 8, 16, 32, 64, 128, 255, 509, 1016, 2028, 4048, ...
nonanacci => 1, 1, 2, 4, 8, 16, 32, 64, 128, 256, 511, 1021, 2040, 4076, ...
decanacci => 1, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1023, 2045, 4088, ...
lucas => 2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322, 521, ...</pre>
 
==={{header|Chipmunk Basic}}===
{{trans|BASIC256}}
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="vbnet">100 sub fib(a())
110 erase f
120 dim f(24)
130 b = 0
140 for x = 1 to ubound(a)
150 b = b+1
160 f(x) = a(x)
170 next x
180 for i = b to 12+b
190 print using "#### ";f(i-b+1);
200 for j = (i-b+1) to i
210 f(i+1) = f(i+1)+f(j)
220 next j
230 next i
240 print
250 end sub
260 cls
270 print " fibonacci =>";
280 dim a(2)
290 a(1) = 1 : a(2) = 1
300 fib(a())
310 print " tribonacci =>";
320 dim a(3)
330 a(1) = 1 : a(2) = 1 : a(3) = 2
340 fib(a())
350 print " tetranacci =>";
360 dim c(4)
370 c(1) = 1 : c(2) = 1 : c(3) = 2 : c(4) = 4
380 fib(c())
390 print " lucas =>";
400 dim d(2)
410 d(1) = 2 : d(2) = 1
420 fib(d())
430 end</syntaxhighlight>
 
==={{header|QBasic}}===
{{trans|BASIC256}}
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
{{works with|QB64}}
<syntaxhighlight lang="qbasic">DECLARE SUB fib (a() AS INTEGER)
 
CLS
PRINT " fibonacci =>";
DIM a(1 TO 2) AS INTEGER
a(1) = 1: a(2) = 1
CALL fib(a())
PRINT " tribonacci =>";
DIM b(1 TO 3) AS INTEGER
b(1) = 1: b(2) = 1: b(3) = 2
CALL fib(b())
PRINT " tetranacci =>";
DIM c(1 TO 4) AS INTEGER
c(1) = 1: c(2) = 1: c(3) = 2: c(4) = 4
CALL fib(c())
PRINT " lucas =>";
DIM d(1 TO 2) AS INTEGER
d(1) = 2: d(2) = 1
CALL fib(d())
END
 
SUB fib (a() AS INTEGER)
DIM f(24)
b = 0
FOR x = 1 TO UBOUND(a)
b = b + 1
f(x) = a(x)
NEXT x
FOR i = b TO 12 + b
PRINT USING "#### "; f(i - b + 1);
FOR j = (i - b + 1) TO i
f(i + 1) = f(i + 1) + f(j)
NEXT j
NEXT i
END SUB</syntaxhighlight>
 
==={{header|QB64}}===
{{trans|BASIC256}}
<syntaxhighlight lang="qbasic">Rem $Dynamic
 
Cls
Print " fibonacci =>";
Dim a(1 To 2) As Integer
a(1) = 1
a(2) = 1
Call fib(a())
Print " tribonacci =>";
ReDim _Preserve a(1 To 3)
a(3) = 2
Call fib(a())
Print " tetranacci =>";
ReDim _Preserve a(1 To 4)
a(4) = 4
Call fib(a())
Print " lucas =>";
ReDim a(1 To 2)
a(1) = 2
a(2) = 1
Call fib(a())
End
 
Sub fib (a() As Integer)
Dim f(24)
b = 0
For x = 1 To UBound(a)
b = b + 1
f(x) = a(x)
Next x
For i = b To 12 + b
Print Using "#### "; f(i - b + 1);
For j = (i - b + 1) To i
f(i + 1) = f(i + 1) + f(j)
Next j
Next i
End Sub</syntaxhighlight>
 
=={{header|Batch File}}==
<syntaxhighlight lang="dos">
@echo off
 
echo Fibonacci Sequence:
call:nfib 1 1
echo.
 
echo Tribonacci Sequence:
call:nfib 1 1 2
echo.
 
echo Tetranacci Sequence:
call:nfib 1 1 2 4
echo.
 
echo Lucas Numbers:
call:nfib 2 1
echo.
 
pause>nul
exit /b
 
:nfib
setlocal enabledelayedexpansion
 
for %%i in (%*) do (
set /a count+=1
set seq=!seq! %%i
)
set "seq=%seq% ^| "
set n=-%count%
set /a n+=1
for %%i in (%*) do (
set F!n!=%%i
set /a n+=1
)
 
for /l %%i in (1,1,10) do (
set /a termstart=%%i-%count%%
set /a termend=%%i-1
for /l %%j in (!termstart!,1,!termend!) do (
set /a F%%i+=!F%%j!
)
set seq=!seq! !F%%i!
)
echo %seq%
 
endlocal
exit /b
</syntaxhighlight>
{{out}}
<pre>
Fibonacci Sequence:
1 1 | 2 3 5 8 13 21 34 55 89 144
 
Tribonacci Sequence:
1 1 2 | 4 7 13 24 44 81 149 274 504 927
 
Tetranacci Sequence:
1 1 2 4 | 8 15 29 56 108 208 401 773 1490 2872
 
Lucas Numbers:
2 1 | 3 4 7 11 18 29 47 76 123 199
</pre>
 
=={{header|BBC BASIC}}==
The BBC BASIC '''SUM''' function is useful here.
<langsyntaxhighlight lang="bbcbasic"> @% = 5 : REM Column width
PRINT "Fibonacci:"
Line 247 ⟶ 1,156:
NEXT
f%(i%-1) = s%
ENDPROC</langsyntaxhighlight>
'''Output:'''
<pre>
Line 259 ⟶ 1,168:
2 1 3 4 7 11 18 29 47 76 123 199 ...
</pre>
 
=={{header|Befunge}}==
 
<syntaxhighlight lang="befunge">110p>>55+109"iccanaceD"22099v
v9013"Tetranacci"9014"Lucas"<
>"iccanobirT"2109"iccanobiF"v
>>:#,_0p20p0>:01-\2>#v0>#g<>>
^_@#:,+55$_^ JH v`1:v#\p03<
_$.1+:77+`^vg03:_0g+>\:1+#^
50p-\30v v\<>\30g1-\^$$_:1-
05g04\g< >`#^_:40p30g0>^!:g</syntaxhighlight>
 
{{out}}
 
<pre>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
Tetranacci 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536
Lucas 2 1 3 4 7 11 18 29 47 76 123 199 322 521 843
Decanacci 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172</pre>
 
=={{header|Bracmat}}==
{{trans|PicoLisp}}
<langsyntaxhighlight lang="bracmat">( ( nacci
= Init Cnt N made tail
. ( plus
Line 302 ⟶ 1,230:
& out$(str$(pad$!name ": ") nacci$(!Init.12))
)
);</langsyntaxhighlight>
Output:
<pre> fibonacci: 1 1 2 3 5 8 13 21 34 55 89 144
Line 315 ⟶ 1,243:
lucas: 2 1 3 4 7 11 18 29 47 76 123 199</pre>
 
=={{header|CBQN}}==
<syntaxhighlight lang="bqn">NStep ← ⊑(1↓⊢∾+´)∘⊢⍟⊣
<lang c>/*29th August, 2012
Nacci ← (2⋆0∾↕)∘(⊢-1˙)
Abhishek Ghosh
 
>((↕10) NStep¨ <)¨ (Nacci¨ 2‿3‿4) ∾ <2‿1</syntaxhighlight>
{{out}}
<pre>┌─
╵ 1 1 2 3 5 8 13 21 34 55
1 1 2 4 7 13 24 44 81 149
1 1 2 4 8 15 29 56 108 208
2 1 3 4 7 11 18 29 47 76
┘</pre>
 
=={{header|C}}==
<syntaxhighlight lang="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 360 ⟶ 1,299:
 
return 0;
}</langsyntaxhighlight>
 
Output:
Line 377 ⟶ 1,316:
55 149 208 76
</pre>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Fibonacci
{
class Program
{
static void Main(string[] args)
{
PrintNumberSequence("Fibonacci", GetNnacciNumbers(2, 10));
PrintNumberSequence("Lucas", GetLucasNumbers(10));
PrintNumberSequence("Tribonacci", GetNnacciNumbers(3, 10));
PrintNumberSequence("Tetranacci", GetNnacciNumbers(4, 10));
Console.ReadKey();
}
 
private static IList<ulong> GetLucasNumbers(int length)
{
IList<ulong> seedSequence = new List<ulong>() { 2, 1 };
return GetFibLikeSequence(seedSequence, length);
}
 
private static IList<ulong> GetNnacciNumbers(int seedLength, int length)
{
return GetFibLikeSequence(GetNacciSeed(seedLength), length);
}
 
private static IList<ulong> GetNacciSeed(int seedLength)
{
IList<ulong> seedSquence = new List<ulong>() { 1 };
 
for (uint i = 0; i < seedLength - 1; i++)
{
seedSquence.Add((ulong)Math.Pow(2, i));
}
 
return seedSquence;
}
 
private static IList<ulong> GetFibLikeSequence(IList<ulong> seedSequence, int length)
{
IList<ulong> sequence = new List<ulong>();
 
int count = seedSequence.Count();
 
if (length <= count)
{
sequence = seedSequence.Take((int)length).ToList();
}
else
{
sequence = seedSequence;
 
for (int i = count; i < length; i++)
{
ulong num = 0;
 
for (int j = 0; j < count; j++)
{
num += sequence[sequence.Count - 1 - j];
}
 
sequence.Add(num);
}
}
 
return sequence;
}
 
private static void PrintNumberSequence(string Title, IList<ulong> numbersequence)
{
StringBuilder output = new StringBuilder(Title).Append(" ");
 
foreach (long item in numbersequence)
{
output.AppendFormat("{0}, ", item);
}
 
Console.WriteLine(output.ToString());
}
}
}</syntaxhighlight>
<pre>Fibonacci 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,
Lucas 2, 1, 3, 4, 7, 11, 18, 29, 47, 76,
Tribonacci 1, 1, 2, 4, 7, 13, 24, 44, 81, 149,
Tetranacci 1, 1, 2, 4, 8, 15, 29, 56, 108, 208,</pre>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <vector>
#include <iostream>
#include <numeric>
Line 428 ⟶ 1,457:
}
return 0 ;
}</langsyntaxhighlight>
Output:
<pre>fibonacci : 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
Line 453 ⟶ 1,482:
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.
 
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <vector>
Line 519 ⟶ 1,548:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp}}==
<lang csharp>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Fibonacci
{
class Program
{
static void Main(string[] args)
{
PrintNumberSequence("Fibonacci", GetNnacciNumbers(2, 10));
PrintNumberSequence("Lucas", GetLucasNumbers(10));
PrintNumberSequence("Tribonacci", GetNnacciNumbers(3, 10));
PrintNumberSequence("Tetranacci", GetNnacciNumbers(4, 10));
Console.ReadKey();
}
 
private static IList<ulong> GetLucasNumbers(int length)
{
IList<ulong> seedSequence = new List<ulong>() { 2, 1 };
return GetFibLikeSequence(seedSequence, length);
}
 
private static IList<ulong> GetNnacciNumbers(int seedLength, int length)
{
return GetFibLikeSequence(GetNacciSeed(seedLength), length);
}
 
private static IList<ulong> GetNacciSeed(int seedLength)
{
IList<ulong> seedSquence = new List<ulong>() { 1 };
 
for (uint i = 0; i < seedLength - 1; i++)
{
seedSquence.Add((ulong)Math.Pow(2, i));
}
 
return seedSquence;
}
 
private static IList<ulong> GetFibLikeSequence(IList<ulong> seedSequence, int length)
{
IList<ulong> sequence = new List<ulong>();
 
int count = seedSequence.Count();
 
if (length <= count)
{
sequence = seedSequence.Take((int)length).ToList();
}
else
{
sequence = seedSequence;
 
for (int i = count; i < length; i++)
{
ulong num = 0;
 
for (int j = 0; j < count; j++)
{
num += sequence[sequence.Count - 1 - j];
}
 
sequence.Add(num);
}
}
 
return sequence;
}
 
private static void PrintNumberSequence(string Title, IList<ulong> numbersequence)
{
StringBuilder output = new StringBuilder(Title).Append(" ");
 
foreach (long item in numbersequence)
{
output.AppendFormat("{0}, ", item);
}
 
Console.WriteLine(output.ToString());
}
}
}</lang>
<pre>Fibonacci 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,
Lucas 2, 1, 3, 4, 7, 11, 18, 29, 47, 76,
Tribonacci 1, 1, 2, 4, 7, 13, 24, 44, 81, 149,
Tetranacci 1, 1, 2, 4, 8, 15, 29, 56, 108, 208,</pre>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn nacci [init]
(letfn [(s [] (lazy-cat init (apply map + (map #(drop % (s)) (range (count init))))))]
(s)))
Line 620 ⟶ 1,559:
(show "Tribonacci" [1 1 2])
(show "Tetranacci" [1 1 2 4])
(show "Lucas" [2 1]))</langsyntaxhighlight>
{{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 627 ⟶ 1,566:
first 20 Lucas (2 1 3 4 7 11 18 29 47 76 123 199 322 521 843 1364 2207 3571 5778 9349)</pre>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">% Find the Nth element of a given n-step sequence
n_step = proc (seq: sequence[int], n: int) returns (int)
a: array[int] := sequence[int]$s2a(seq)
for i: int in int$from_to(1,n) do
sum: int := 0
for x: int in array[int]$elements(a) do
sum := sum + x
end
array[int]$reml(a)
array[int]$addh(a,sum)
end
return(array[int]$bottom(a))
end n_step
 
% Generate the initial sequence for the Fibonacci n-step sequence of length N
anynacci = proc (n: int) returns (sequence[int])
a: array[int] := array[int]$[1]
for i: int in int$from_to(0,n-2) do
array[int]$addh(a, 2**i)
end
return(sequence[int]$a2s(a))
end anynacci
 
% Given an initial sequence, print the first N elements
print_n = proc (seq: sequence[int], n: int)
po: stream := stream$primary_output()
for i: int in int$from_to(0, n-1) do
stream$putright(po, int$unparse(n_step(seq, i)), 4)
end
stream$putl(po, "")
end print_n
 
start_up = proc ()
s = struct[name: string, seq: sequence[int]]
po: stream := stream$primary_output()
seqs: array[s] := array[s]$[
s${name: "Fibonacci", seq: anynacci(2)},
s${name: "Tribonacci", seq: anynacci(3)},
s${name: "Tetranacci", seq: anynacci(4)},
s${name: "Lucas", seq: sequence[int]$[2,1]}
]
for seq: s in array[s]$elements(seqs) do
stream$putleft(po, seq.name, 12)
print_n(seq.seq, 10)
end
end start_up</syntaxhighlight>
{{out}}
<pre>Fibonacci 1 1 2 3 5 8 13 21 34 55
Tribonacci 1 1 2 4 7 13 24 44 81 149
Tetranacci 1 1 2 4 8 15 29 56 108 208
Lucas 2 1 3 4 7 11 18 29 47 76</pre>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">
(defun gen-fib (lst m)
"Return the first m members of a generalized Fibonacci sequence using lst as initial values
Line 647 ⟶ 1,639:
(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))))</langsyntaxhighlight>
{{out}}
<pre>Lucas series: (2 1 3 4 7 11 18 29 47 76)
Line 653 ⟶ 1,645:
Fibonacci 3-step sequence: (1 1 2 4 7 13 24 44 81 149)
Fibonacci 4-step sequence: (1 1 2 4 8 15 29 56 108 208)</pre>
 
=={{header|D}}==
===Basic Memoization===
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm, std.range, std.conv;
 
Line 683 ⟶ 1,676:
15.iota.map!fibber);
}
}</langsyntaxhighlight>
{{out}}
<pre>[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Line 699 ⟶ 1,692:
===Callable Struct===
The output is similar.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.conv;
 
struct fiblike(T) {
Line 733 ⟶ 1,726:
n, name, 15.iota.map!fib);
}
}</langsyntaxhighlight>
 
===Struct With opApply===
The output is similar.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.traits;
 
struct Fiblike(T) {
Line 780 ⟶ 1,773:
writefln("n=%2d, %5snacci -> %s", n, name, fib.takeApply(15));
}
}</langsyntaxhighlight>
 
===Range Generator Version===
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm, std.range, std.concurrency;
 
Line 801 ⟶ 1,794:
writefln("n=%2d, %5snacci -> %(%s, %), ...", n, name, fib.take(15));
}
}</langsyntaxhighlight>
{{out}}
<pre>[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Line 814 ⟶ 1,807:
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, ...</pre>
=={{header|Delphi}}==
See [[#Pascal]].
=={{header|EasyLang}}==
<syntaxhighlight>
proc sequ n$ val[] n . .
write n$ & ": "
il = len val[]
len val[] n
for i = il + 1 to n
for j = 1 to il
val[i] += val[i - j]
.
.
for v in val[]
write v & " "
.
print ""
.
sequ "Fibonacci" [ 1 1 ] 10
sequ "Tribonacci" [ 1 1 2 ] 10
sequ "Tetrabonacci" [ 1 1 2 4 ] 10
sequ "Lucas" [ 2 1 ] 10
</syntaxhighlight>
{{out}}
<pre>
Fibonacci: 1 1 2 3 5 8 13 21 34 55
Tribonacci: 1 1 2 4 7 13 24 44 81 149
Tetrabonacci: 1 1 2 4 8 15 29 56 108 208
Lucas: 2 1 3 4 7 11 18 29 47 76
</pre>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
;; generate a recursive lambda() for a x-nacci
;; equip it with memoïzation
Line 840 ⟶ 1,863:
(make-nacci name seed)
(printf "%s[%d] → %d" name (vector-length seed) (take name 16))))
</syntaxhighlight>
</lang>
{{out}}
Line 856 ⟶ 1,879:
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule RC do
def anynacci(start_sequence, count) do
n = length(start_sequence)
Line 884 ⟶ 1,907:
:io.format("~11s: ", [name])
IO.inspect RC.anynacci(list, 15)
end)</langsyntaxhighlight>
 
{{out}}
Line 901 ⟶ 1,924:
 
=={{header|Erlang}}==
<syntaxhighlight lang="text">
-module( fibonacci_nstep ).
 
Line 923 ⟶ 1,946:
{Sum_ns, _Not_sum_ns} = lists:split( Nth, Ns ),
{Nth, [lists:sum(Sum_ns) | Ns]}.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 934 ⟶ 1,957:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM FIBON
 
Line 978 ⟶ 2,001:
FIB("Lucas","2,1")
END PROGRAM
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let fibinit = Seq.append (Seq.singleton 1) (Seq.unfold (fun n -> Some(n, 2*n)) 1)
 
let fiblike init =
Line 1,004 ⟶ 2,027:
(Seq.init prefix.Length (fun i -> (prefix.[i], i+2)))
printfn " lucas -> %A" (start (fiblike [2; 1]))
0</langsyntaxhighlight>
Output
<pre>n= 2, fibonacci -> [1; 1; 2; 3; 5; 8; 13; 21; 34; 55; 89; 144; 233; 377; 610]
Line 1,016 ⟶ 2,039:
n=10, decanacci -> [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]</pre>
 
=={{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.
<syntaxhighlight lang="factor">USING: formatting fry kernel make math namespaces qw sequences ;
 
: n-bonacci ( n initial -- seq ) [
[ [ , ] each ] [ length - ] [ length ] tri
'[ building get _ tail* sum , ] times
] { } make ;
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</syntaxhighlight>
{{out}}
<pre>
fibonacci { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 }
tribonacci { 1, 1, 2, 4, 7, 13, 24, 44, 81, 149 }
tetranacci { 1, 1, 2, 4, 8, 15, 29, 56, 108, 208 }
lucas { 2, 1, 3, 4, 7, 11, 18, 29, 47, 76 }
</pre>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: length @ ; \ length of an array is stored at its address
: a{ here cell allot ;
: } , here over - cell / over ! ;
Line 1,042 ⟶ 2,085:
." tetranacci: " a{ 1 , 1 , 2 , 4 } show-nacci
." lucas: " a{ 2 , 1 } show-nacci
</syntaxhighlight>
</lang>
{{out}}
<pre>fibonacci: 1 1 2 3 5 8 13 21 34 55
Line 1,051 ⟶ 2,094:
 
=={{header|Fortran}}==
<langsyntaxhighlight lang="fortran">
! save this program as file f.f08
! gnu-linux command to build and test
Line 1,116 ⟶ 2,159:
end subroutine nacci
end program f
</syntaxhighlight>
</lang>
 
<pre>
Line 1,155 ⟶ 2,198:
1 1 2 4
1 1 2 4 8 15 29 56 108 208
</pre>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' Deduces the step, n, from the length of the dynamic array passed in
' and fills it out to 'size' elements
Sub fibN (a() As Integer, size As Integer)
Dim lb As Integer = LBound(a)
Dim ub As Integer = UBound(a)
Dim length As Integer = ub - lb + 1
If length < 2 OrElse length >= size Then Return
ub = lb + size - 1
Redim Preserve a(lb To ub)
Dim sum As Integer
For i As Integer = lb + length to ub
sum = 0
For j As Integer = 1 To Length
sum += a(i - j)
Next j
a(i) = sum
Next i
End Sub
 
Sub printSeries(a() As Integer, name_ As String) '' name is a keyword
Print name_; " =>";
For i As Integer = LBound(a) To UBound(a)
Print Using "####"; a(i);
Print " ";
Next
Print
End Sub
 
Const size As Integer = 13 '' say
Redim a(1 To 2) As Integer
a(1) = 1 : a(2) = 1
fibN(a(), size)
printSeries(a(), "fibonacci ")
Redim Preserve a(1 To 3)
a(3) = 2
fibN(a(), size)
printSeries(a(), "tribonacci")
Redim Preserve a(1 To 4)
a(4) = 4
fibN(a(), size)
printSeries(a(), "tetranacci")
erase a
Redim a(1 To 2)
a(1) = 2 : a(2) = 1
fibN(a(), size)
printSeries(a(), "lucas ")
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
{{out}}
<pre>
fibonacci => 1 1 2 3 5 8 13 21 34 55 89 144 233
tribonacci => 1 1 2 4 7 13 24 44 81 149 274 504 927
tetranacci => 1 1 2 4 8 15 29 56 108 208 401 773 1490
lucas => 2 1 3 4 7 11 18 29 47 76 123 199 322
</pre>
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">import util.TextTable
native scala.collection.mutable.Queue
 
Line 1,188 ⟶ 2,292:
t.row( ([k] + [seqs(i)(k) | i <- 0:4]).toIndexedSeq() )
 
print( t )</langsyntaxhighlight>
 
{{out}}
Line 1,208 ⟶ 2,312:
+----+-----------+------------+------------+-------+
</pre>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Fibonacci_n-step_number_sequences}}
 
'''Solution'''
 
According to the requirements, the program must generate a series, and the order (Fibonacci, Tribonacci, etc) should be determined according with the initial values.
 
In this case, the number n indicates how many terms of the series will be generated.
 
[[File:Fōrmulæ - Fibonacci n-step number sequences 01.png]]
 
The following generates a Fibonacci series of 15 terms:
 
[[File:Fōrmulæ - Fibonacci n-step number sequences 02.png]]
 
[[File:Fōrmulæ - Fibonacci n-step number sequences 03.png]]
 
The following generates a Lucas series of 15 terms:
 
[[File:Fōrmulæ - Fibonacci n-step number sequences 04.png]]
 
[[File:Fōrmulæ - Fibonacci n-step number sequences 05.png]]
 
The following generates a Tribonacci series of 15 terms:
 
[[File:Fōrmulæ - Fibonacci n-step number sequences 06.png]]
 
[[File:Fōrmulæ - Fibonacci n-step number sequences 07.png]]
 
'''Generating initial values.''' The initial values can be generated by the following function:
 
[[File:Fōrmulæ - Fibonacci n-step number sequences 08.png]]
 
Note that it is a recursive function, and it calls the previously defined function. It requires the initial values as a seed: (1, 1) for Fibonacci style (Fibonacci, Tribonacci, etc), and (2, 1) for Lucas style.
 
The following generates the initial values for Fibonacci series.
 
[[File:Fōrmulæ - Fibonacci n-step number sequences 09.png]]
 
[[File:Fōrmulæ - Fibonacci n-step number sequences 10.png]]
 
The following generates the initial values for Lucas series.
 
[[File:Fōrmulæ - Fibonacci n-step number sequences 11.png]]
 
[[File:Fōrmulæ - Fibonacci n-step number sequences 12.png]]
 
'''Generating tables of series for Fibonacci and Lucas'''
 
This generates a tables of series for Fibonacci (15 terms), for orders 2 to 10 (Fibonacci, Tribonacci, etc.)
 
[[File:Fōrmulæ - Fibonacci n-step number sequences 13.png]]
 
[[File:Fōrmulæ - Fibonacci n-step number sequences 14.png]]
 
This generates a tables of series for Lucas (15 terms), for orders 2 to 15:
 
[[File:Fōrmulæ - Fibonacci n-step number sequences 15.png]]
 
[[File:Fōrmulæ - Fibonacci n-step number sequences 16.png]]
 
=={{header|Go}}==
Solution using a separate goroutinegoroutines.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
 
func g(i []int, c chan<- int) {
var sum int
b := append([]int{}(nil), i...) // make a copy
for _, t := range b {
c <- t
sum += t
}
}
for {
for j, t := range b {
c <- sum
b[j], sum = sum, sum+sum-t
}
}
}
}
}
 
func main() {
for _, s := range [...]struct {
seq string
i []int
} {
{"Fibonacci", []int{1, 1}},
{"Tribonacci", []int{1, 1, 2}},
{"Tetranacci", []int{1, 1, 2, 4}},
{"Lucas", []int{2, 1}},
} {
fmt.Printf("%10s:", s.seq)
c := make(chan int)
// Note/warning: these goroutines are leaked.
go g(s.i, c)
go g(s.i, c)
for j := 0; j < 10; j++ {
for j := 0; j < 10; j++ {
fmt.Print(" ", <-c)
fmt.Print(" ", <-c)
}
}
fmt.Println()
fmt.Println()
}
}
}</lang>
}</syntaxhighlight>
{{out}}
<pre>
Line 1,259 ⟶ 2,426:
=={{header|Groovy}}==
=====Solution=====
<langsyntaxhighlight lang="groovy">def fib = { List seed, int k=10 ->
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 1,272 ⟶ 2,439:
}
}
}</langsyntaxhighlight>
=====Test=====
<langsyntaxhighlight lang="groovy">[
' fibonacci':[1,1],
'tribonacci':[1,1,2],
Line 1,290 ⟶ 2,457:
 
println " lucas[0]: ${fib([2,1],0)}"
println " tetra[3]: ${fib([1,1,2,4],3)}"</langsyntaxhighlight>
{{out}}
<pre> fibonacci: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Line 1,306 ⟶ 2,473:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import DataControl.ListMonad (tailszipWithM_)
import ControlData.MonadList (zipWithM_tails)
 
fiblike :: [Integer] -> [Integer]
fiblike st = xs where
where
xs = st ++ map (sum . take n) (tails xs)
xs = st <> map (sum . take n) (tails xs)
n = length st
n = length st
 
nstep :: Int -> [Integer]
nstep n = fiblike $ take n $ 1 : iterate (2 *) 1
 
main :: IO ()
main = do
mapM_ (print $. take 10 $. fiblike) [[1, 1], [2, 1]]
zipWithM_
print $ take 10 $ fiblike [2,1]
zipWithM_ ( \n name -> do putStr (name ++ "nacci -> ")
putStr (name <> "nacci -> ")
print $ take 15 $ nstep n)
print $ take 15 $ nstep n
[2..] (words "fibo tribo tetra penta hexa hepta octo nona deca")</lang>
)
[2 ..]
(words "fibo tribo tetra penta hexa hepta octo nona deca")</syntaxhighlight>
{{out}}
<pre>
Line 1,338 ⟶ 2,509:
decanacci -> [1,1,2,4,8,16,32,64,128,256,512,1023,2045,4088,8172]
</pre>
 
Or alternatively, without imports – using only the default Prelude:
<syntaxhighlight lang="haskell">------------ FIBONACCI N-STEP NUMBER SEQUENCES -----------
 
nStepFibonacci :: Int -> [Int]
nStepFibonacci =
nFibs
. (1 :)
. fmap (2 ^)
. enumFromTo 0
. subtract 2
 
nFibs :: [Int] -> [Int]
nFibs ys@(z : zs) = z : nFibs (zs <> [sum ys])
 
--------------------------- TEST -------------------------
main :: IO ()
main = do
putStrLn $
justifyLeft 12 ' ' "Lucas" <> "-> "
<> show (take 15 (nFibs [2, 1]))
(putStrLn . unlines)
( zipWith
( \s n ->
justifyLeft 12 ' ' (s <> "naccci")
<> ("-> " <> show (take 15 (nStepFibonacci n)))
)
( words
"fibo tribo tetra penta hexa hepta octo nona deca"
)
[2 ..]
)
 
justifyLeft :: Int -> Char -> String -> String
justifyLeft n c s = take n (s <> replicate n c)</syntaxhighlight>
<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]
tribonaccci -> [1,1,2,4,7,13,24,44,81,149,274,504,927,1705,3136]
tetranaccci -> [1,1,2,4,8,15,29,56,108,208,401,773,1490,2872,5536]
pentanaccci -> [1,1,2,4,8,16,31,61,120,236,464,912,1793,3525,6930]
hexanaccci -> [1,1,2,4,8,16,32,63,125,248,492,976,1936,3840,7617]
heptanaccci -> [1,1,2,4,8,16,32,64,127,253,504,1004,2000,3984,7936]
octonaccci -> [1,1,2,4,8,16,32,64,128,255,509,1016,2028,4048,8080]
nonanaccci -> [1,1,2,4,8,16,32,64,128,256,511,1021,2040,4076,8144]
decanaccci -> [1,1,2,4,8,16,32,64,128,256,512,1023,2045,4088,8172]</pre>
 
or in terms of '''unfoldr''':
{{Trans|Python}}
<syntaxhighlight lang="haskell">import Data.Bifunctor (second)
import Data.List (transpose, uncons, unfoldr)
 
------------ FIBONACCI N-STEP NUMBER SEQUENCES -----------
 
a000032 :: [Int]
a000032 = unfoldr (recurrence 2) [2, 1]
 
nStepFibonacci :: Int -> [Int]
nStepFibonacci =
unfoldr <$> recurrence
<*> (($ 1 : fmap (2 ^) [0 ..]) . take)
 
recurrence :: Int -> [Int] -> Maybe (Int, [Int])
recurrence n =
( fmap
. second
. flip (<>)
. pure
. sum
. take n
)
<*> uncons
 
--------------------------- TEST -------------------------
main :: IO ()
main =
putStrLn $
"Recurrence relation sequences:\n\n"
<> spacedTable
justifyRight
( ("lucas:" : fmap show (take 15 a000032)) :
zipWith
( \k n ->
(k <> "nacci:") :
fmap
show
(take 15 $ nStepFibonacci n)
)
(words "fibo tribo tetra penta hexa hepta octo nona deca")
[2 ..]
)
 
------------------------ FORMATTING ----------------------
spacedTable ::
(Int -> Char -> String -> String) -> [[String]] -> String
spacedTable aligned rows =
let columnWidths =
fmap
(maximum . fmap length)
(transpose rows)
in unlines $
fmap
(unwords . zipWith (`aligned` ' ') columnWidths)
rows
 
justifyRight :: Int -> Char -> String -> String
justifyRight n c = (drop . length) <*> (replicate n c <>)</syntaxhighlight>
{{Out}}
<pre>Recurrence relation sequences:
 
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
tribonacci: 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136
tetranacci: 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536
pentanacci: 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930
hexanacci: 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617
heptanacci: 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936
octonacci: 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080
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</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
 
Works in both languages:
<langsyntaxhighlight lang="unicon">procedure main(A)
every writes("F2:\t"|right((fnsGen(1,1))\14,5) | "\n")
every writes("F3:\t"|right((fnsGen(1,1,2))\14,5) | "\n")
Line 1,356 ⟶ 2,646:
suspend cache[i]
}
end</langsyntaxhighlight>
 
Output:
Line 1,371 ⟶ 2,661:
A slightly longer version of <tt>fnsGen</tt> that reduces the memory
footprint is:
<langsyntaxhighlight lang="unicon">procedure fnsGen(cache[])
every i := seq() do {
if i := (i > *cache, *cache) then {
Line 1,380 ⟶ 2,670:
suspend cache[i]
}
end</langsyntaxhighlight>
 
The output is identical.
Line 1,386 ⟶ 2,676:
=={{header|J}}==
 
'''Solution''':<langsyntaxhighlight lang="j"> nacci =: (] , +/@{.)^:(-@#@]`(-#)`])</langsyntaxhighlight>
'''Example''' ''(Lucas)'':<langsyntaxhighlight lang="j"> 10 nacci 2 1 NB. Lucas series, first 10 terms
2 1 3 4 7 11 18 29 47 76</langsyntaxhighlight>
'''Example''' ''(extended 'nacci series)'':<langsyntaxhighlight lang="j"> TESTS =: }."1 fixdsv noun define [ require 'tables/dsv' NB. Tests from task description
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 1,411 ⟶ 2,701:
octonacci ✓
nonanacci ✓
decanacci ✓</langsyntaxhighlight>
 
=={{header|Java}}==
Line 1,417 ⟶ 2,707:
'''Code:'''
 
<langsyntaxhighlight lang="java">class Fibonacci
{
public static int[] lucas(int n, int numRequested)
Line 1,461 ⟶ 2,751:
}
}
}</langsyntaxhighlight>
 
Output:
Line 1,482 ⟶ 2,772:
lucas(9): 2 1 3 6 12 24 48 96 192 384 766 1531 3059 6112 12212
lucas(10): 2 1 3 6 12 24 48 96 192 384 768 1534 3067 6131 12256</pre>
 
 
=={{header|JavaScript}}==
===ES5===
 
<syntaxhighlight lang="javascript">function fib(arity, len) {
 
<lang JavaScript>function fib(arity, len) {
return nacci(nacci([1,1], arity, arity), arity, len);
}
Line 1,512 ⟶ 2,800:
}
 
main();</langsyntaxhighlight>
{{out}}
<pre>fib(2): 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610
Line 1,532 ⟶ 2,820:
lucas(9): 2,1,3,6,12,24,48,96,192,384,766,1531,3059,6112,12212
lucas(10): 2,1,3,6,12,24,48,96,192,384,768,1534,3067,6131,12256</pre>
 
===ES6===
<syntaxhighlight lang="javascript">(() => {
'use strict';
 
// Start sequence -> Number of terms -> terms
 
// takeNFibs :: [Int] -> Int -> [Int]
const takeNFibs = (xs, n) => {
const go = (xs, n) =>
0 < n && 0 < xs.length ? (
cons(
head(xs),
go(
append(tail(xs), [sum(xs)]),
n - 1
)
)
) : [];
return go(xs, n);
};
 
// fibInit :: Int -> [Int]
const fibInit = n =>
cons(
1,
map(x => Math.pow(2, x),
enumFromToInt(0, n - 2)
)
);
 
// TEST -----------------------------------------------------------------
const main = () => {
const
intTerms = 15,
strTable = unlines(
zipWith(
(s, n) =>
justifyLeft(12, ' ', s + 'nacci') + ' -> ' +
showJSON(
takeNFibs(fibInit(n), intTerms)
),
words('fibo tribo tetra penta hexa hepta octo nona deca'),
enumFromToInt(2, 10)
)
);
 
return justifyLeft(12, ' ', 'Lucas ') + ' -> ' +
showJSON(takeNFibs([2, 1], intTerms)) + '\n' +
strTable;
};
 
// GENERIC FUNCTIONS ----------------------------
 
// append (++) :: [a] -> [a] -> [a]
// append (++) :: String -> String -> String
const append = (xs, ys) => xs.concat(ys);
 
// cons :: a -> [a] -> [a]
const cons = (x, xs) =>
Array.isArray(xs) ? (
[x].concat(xs)
) : (x + xs);
 
// enumFromToInt :: Int -> Int -> [Int]
const enumFromToInt = (m, n) =>
m <= n ? iterateUntil(
x => n <= x,
x => 1 + x,
m
) : [];
 
// head :: [a] -> a
const head = xs => xs.length ? xs[0] : undefined;
 
// iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]
const iterateUntil = (p, f, x) => {
const vs = [x];
let h = x;
while (!p(h))(h = f(h), vs.push(h));
return vs;
};
 
// justifyLeft :: Int -> Char -> String -> String
const justifyLeft = (n, cFiller, s) =>
n > s.length ? (
s.padEnd(n, cFiller)
) : s;
 
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);
 
// showJSON :: a -> String
const showJSON = x => JSON.stringify(x);
 
// sum :: [Num] -> Num
const sum = xs => xs.reduce((a, x) => a + x, 0);
 
// tail :: [a] -> [a]
const tail = xs => 0 < xs.length ? xs.slice(1) : [];
 
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
 
// words :: String -> [String]
const words = s => s.split(/\s+/);
 
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = (f, xs, ys) =>
Array.from({
length: Math.min(xs.length, ys.length)
}, (_, i) => f(xs[i], ys[i], i));
 
// MAIN ---
return main();
})();</syntaxhighlight>
<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]
tribonacci -> [1,1,2,4,7,13,24,44,81,149,274,504,927,1705,3136]
tetranacci -> [1,1,2,4,8,15,29,56,108,208,401,773,1490,2872,5536]
pentanacci -> [1,1,2,4,8,16,31,61,120,236,464,912,1793,3525,6930]
hexanacci -> [1,1,2,4,8,16,32,63,125,248,492,976,1936,3840,7617]
heptanacci -> [1,1,2,4,8,16,32,64,127,253,504,1004,2000,3984,7936]
octonacci -> [1,1,2,4,8,16,32,64,128,255,509,1016,2028,4048,8080]
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]</pre>
 
=={{header|jq}}==
{{Works with|jq|1.4}}
<langsyntaxhighlight lang="jq"># Input: the initial array
def nacci(arity; len):
arity as $arity | len as $len
Line 1,549 ⟶ 2,963:
def lucas(arity; len):
arity as $arity | len as $len
| [2,1] | nacci($arity; $arity) | nacci($arity; $len) ;</langsyntaxhighlight>
'''Example''':
<langsyntaxhighlight lang="jq">def main:
(range(2; 11) | "fib(\(.)): \(fib(.; 15))"),
(range(2; 11) | "lucas(\(.)): \(lucas(.; 15))")
;
 
main</langsyntaxhighlight>
{{Out}}
$ jq -M -r -n -f fibonacci_n-step.jq
Line 1,567 ⟶ 2,981:
 
'''Generalized Fibonacci Iterator Definition'''
<syntaxhighlight lang="julia">
<lang Julia>
type NFib{T<:Integer}
n::T
Line 1,598 ⟶ 3,012:
return (f, fs)
end
</syntaxhighlight>
</lang>
 
'''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">
<lang Julia>
function fib_seeder{T<:Integer}(n::T)
a = zeros(BigInt, n)
Line 1,613 ⟶ 3,027:
NFib(n, k, fib_seeder)
end
</syntaxhighlight>
</lang>
 
'''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">
<lang Julia>
function luc_rc_seeder{T<:Integer}(n::T)
a = zeros(BigInt, n)
Line 1,629 ⟶ 3,043:
NFib(n, k, luc_rc_seeder)
end
</syntaxhighlight>
</lang>
 
'''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">
<lang Julia>
function luc_seeder{T<:Integer}(n::T)
a = -ones(BigInt, n)
Line 1,644 ⟶ 3,058:
NFib(n, k, luc_seeder)
end
</syntaxhighlight>
</lang>
 
'''Main'''
<syntaxhighlight lang="julia">
<lang Julia>
lo = 2
hi = 10
Line 1,683 ⟶ 3,097:
println()
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,719 ⟶ 3,133:
9 => 1 3 7 15 31 63 127 255 511 1013 2025 4047 8087 16159 32287 64511
10 => 1 3 7 15 31 63 127 255 511 1023 2036 4071 8139 16271 32527 65023
</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.2
 
fun fibN(initial: IntArray, numTerms: Int) : IntArray {
val n = initial.size
require(n >= 2 && numTerms >= 0)
val fibs = initial.copyOf(numTerms)
if (numTerms <= n) return fibs
for (i in n until numTerms) {
var sum = 0
for (j in i - n until i) sum += fibs[j]
fibs[i] = sum
}
return fibs
}
 
fun main(args: Array<String>) {
val names = arrayOf("fibonacci", "tribonacci", "tetranacci", "pentanacci", "hexanacci",
"heptanacci", "octonacci", "nonanacci", "decanacci")
val initial = intArrayOf(1, 1, 2, 4, 8, 16, 32, 64, 128, 256)
println(" n name values")
var values = fibN(intArrayOf(2, 1), 15).joinToString(", ")
println("%2d %-10s %s".format(2, "lucas", values))
for (i in 0..8) {
values = fibN(initial.sliceArray(0 until i + 2), 15).joinToString(", ")
println("%2d %-10s %s".format(i + 2, names[i], values))
}
}</syntaxhighlight>
 
{{out}}
<pre>
n name values
2 lucas 2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322, 521, 843
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
4 tetranacci 1, 1, 2, 4, 8, 15, 29, 56, 108, 208, 401, 773, 1490, 2872, 5536
5 pentanacci 1, 1, 2, 4, 8, 16, 31, 61, 120, 236, 464, 912, 1793, 3525, 6930
6 hexanacci 1, 1, 2, 4, 8, 16, 32, 63, 125, 248, 492, 976, 1936, 3840, 7617
7 heptanacci 1, 1, 2, 4, 8, 16, 32, 64, 127, 253, 504, 1004, 2000, 3984, 7936
8 octonacci 1, 1, 2, 4, 8, 16, 32, 64, 128, 255, 509, 1016, 2028, 4048, 8080
9 nonanacci 1, 1, 2, 4, 8, 16, 32, 64, 128, 256, 511, 1021, 2040, 4076, 8144
10 decanacci 1, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1023, 2045, 4088, 8172
</pre>
 
=={{header|Lua}}==
<syntaxhighlight lang Lua="lua">function n_NaccinStepFibs (n, seqLengthseq, lucaslimit)
local seqiMax, nextNumsum = {#seq - 1}
ifwhile lucas#seq then< limit do
seqsum = {2, 1}0
for i = 0, iMax do sum = sum + seq[#seq - i] end
else
for power = 1table.insert(seq, n - 1 dosum)
table.insert(seq, 2 ^ power)
end
end
while #seq < seqLength do
nextNum = 0
for i = #seq - (n-1), #seq do
nextNum = nextNum + seq[i]
end
table.insert(seq, nextNum)
end
return seq
end
 
local fibSeqs = {
function display (t)
{name = "Fibonacci", values = {1, 1} },
print(" n\t|\t\t\tValues")
{name = "Tribonacci", values = {1, 1, 2} },
print(string.rep("-", 75))
{name = "Tetranacci", values = {1, 1, 2, 4}},
for k, v in pairs(t) do
{name = "Lucas", io.write(" " .. k values = {2, "\t|1} ") }
}
for _, val in pairs(v) do
for _, sequence in pairs(fibSeqs) do
io.write(val .. " ")
io.write(sequence.name .. ": ")
end
print(".table.concat(nStepFibs(sequence.values, 10), " "))
end</syntaxhighlight>
end
end
 
local nacciTab = {}
for n = 2, 10 do
nacciTab[n] = n_Nacci(n, 16) -- 16 of each fits in one cmd line
end
nacciTab.lucas = n_Nacci(2, 16, "lucas")
display(nacciTab)
</lang>
{{out}}
<pre>Fibonacci: n1 1 2 3 5 8 |13 21 34 Values55
Tribonacci: 1 1 2 4 7 13 24 44 81 149
---------------------------------------------------------------------------
Tetranacci: 1 1 2 4 8 15 29 56 108 208
2 | 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 ...
Lucas: 2 1 3 4 7 11 18 29 47 76</pre>
3 | 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 5768 10609 ...
4 | 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 10671 20569 ...
5 | 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 13624 26784 ...
6 | 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 15109 29970 ...
7 | 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 15808 31489 ...
8 | 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 16128 32192 ...
9 | 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 16272 32512 ...
10 | 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 16336 32656 ...
lucas | 2 1 3 4 7 11 18 29 47 76 123 199 322 521 843 1364 ...</pre>
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">numSequence := proc(initValues :: Array)
local n, i, values;
n := numelems(initValues);
Line 1,790 ⟶ 3,222:
printf ("nacci(%d): %a\n", i, convert(numSequence(initValues), list));
end do:
printf ("lucas: %a\n", convert(numSequence(Array([2, 1])), list));</langsyntaxhighlight>
{{out}}
<pre>
Line 1,806 ⟶ 3,238:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">
<lang Mathematica>
f2=Function[{l,k},
Module[{n=Length@l,m},
Line 1,813 ⟶ 3,245:
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>
</lang>
Output:
<pre>
Line 1,840 ⟶ 3,272:
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import sequtils, strutils
 
proc fiblike(start: seq[int]): auto =
Line 1,849 ⟶ 3,281:
else:
var ans = 0
for i in n-start.len .. < n:
ans += fibber(i)
memo.add ans
Line 1,866 ⟶ 3,298:
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(" "), " ..."</syntaxhighlight>
", toSeq(0..14).mapIt(string, $fibber(it)).join(" "), " ..."</lang>
Output:
<pre>@[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Line 1,880 ⟶ 3,311:
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 ...</pre>
 
=={{header|Ol}}==
We will use lazy lists, so can get any amount of n-nacci numbers.
 
<syntaxhighlight lang="scheme">
(define (n-fib-iterator ll)
(cons (car ll)
(lambda ()
(n-fib-iterator (append (cdr ll) (list (fold + 0 ll)))))))
</syntaxhighlight>
 
Testing:
<syntaxhighlight lang="scheme">
(print "2, fibonacci : " (ltake (n-fib-iterator '(1 1)) 15))
(print "3, tribonacci: " (ltake (n-fib-iterator '(1 1 2)) 15))
(print "4, tetranacci: " (ltake (n-fib-iterator '(1 1 2 4)) 15))
(print "5, pentanacci: " (ltake (n-fib-iterator '(1 1 2 4 8)) 15))
(print "2, lucas : " (ltake (n-fib-iterator '(2 1)) 15))
 
; ==>
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)
4, tetranacci: (1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536)
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 1,885 ⟶ 3,342:
 
Use genV if you prefer to supply a different starting vector.
<langsyntaxhighlight lang="parigp">gen(n)=k->my(v=vector(k,i,1));for(i=3,min(k,n),v[i]=2^(i-2));for(i=n+1,k,v[i]=sum(j=i-n,i-1,v[j]));v
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)))</langsyntaxhighlight>
{{out}}
<pre>2 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Line 1,901 ⟶ 3,358:
=={{header|Pascal}}==
{{works with|Free_Pascal}}
<langsyntaxhighlight lang="pascal">program FibbonacciN (output);
 
type
Line 1,970 ⟶ 3,427:
write(sequence[k], ' ');
writeln;
end.</langsyntaxhighlight>
Output:
<pre>% ./Fibbonacci
Line 1,991 ⟶ 3,448:
Fib(n)/Fib(n-1) tends to the golden ratio = 1.618... 1.618^100 > 2^64
{{works with|Free_Pascal}}
<langsyntaxhighlight lang="pascal">
program FibbonacciN (output);
{$IFNDEF FPC}
Line 2,104 ⟶ 3,561:
write(NextNacci(Nacci),' ');
writeln;
END.</langsyntaxhighlight>
 
=={{header|PerlPascalABC.NET}}==
===Unfold===
<lang perl>use 5.010;
I first define a high order function to generate infinite sequences given a lambda and a seed.
 
<syntaxhighlight lang="pascal">
use List::Util qw/max sum/;
// unfold infinite sequences. Nigel Galloway: September 8th., 2022
 
function unfold<gN,gG>(n:Func<gG,(gN,gG)>; g:gG): sequence of gN;
sub fib {
begin
my $n = shift;
var (x,r):=n(g);
my $xs = shift // [1];
yield x;
my @xs = @{$xs};
yield sequence unfold(n,r);
 
end;
while (my $len = scalar @xs) {
function unfold<gN,gG>(n:Func<array of gG,(gN,array of gG)>;params g:array of gG): sequence of gN := unfold(n,g);
last if $len >= 20;
</syntaxhighlight>
push(
@xs,
sum(@xs[max($len - $n, 0)..$len-1])
);
}
return @xs;
}
 
for (2..10) {
say join(' ', fib($_));
}
say join(' ', fib(2, [2,1]));</lang>
 
===The Task===
Like the Pascal above but not iffy, not loopy, and not as long!
<syntaxhighlight lang="pascal">
// Fibonacci n-step number sequences. Nigel Galloway: September 8th., 2022
var nFib:=function(n:array of biginteger): (biginteger,array of biginteger)->(n.First,n[1:].Append(n.Sum).ToArray);
begin
var fib:=unfold(nFib,1bi,1bi);
fib.Take(20).Println;
var tri:=unfold(nFib,fib.Take(3));
tri.Take(20).Println;
var tet:=unfold(nFib,tri.Take(4));
tet.Take(20).Println;
var pen:=unfold(nFib,tet.Take(5));
pen.Take(20).Println;
var hex:=unfold(nFib,pen.Take(6));
hex.Take(20).Println;
var hep:=unfold(nFib,hex.Take(7));
hep.Take(20).Println;
var oct:=unfold(nFib,hep.Take(8));
oct.Take(20).Println;
var non:=unfold(nFib,oct.Take(9));
non.Take(20).Println;
var dec:=unfold(nFib,non.Take(10));
dec.Take(20).Println;
var luc:=unfold(nFib,2bi,1bi);
luc.Take(20).Println;
end.
</syntaxhighlight>
{{out}}
<pre>
<pre>1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 5768 10609 19513 35890 66012
1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 10671 20569 39648 76424 147312
Line 2,142 ⟶ 3,616:
1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 16272 32512 64960 129792 259328
1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 16336 32656 65280 130496 260864
2 1 3 4 7 11 18 29 47 76 123 199 322 521 843 1364 2207 3571 5778 9349</pre>
</pre>
 
=={{header|Perl 6}}==
<syntaxhighlight lang="perl">use strict;
use warnings;
use feature <say signatures>;
no warnings 'experimental';
use List::Util <max sum>;
 
sub fib_n ($n = 2, $xs = [1], $max = 100) {
===Lazy List with Closure===
my @xs = @$xs;
<lang perl6>sub fibo ($n) {
constantwhile @starters( $max > (my $len = 1,1,2,4@xs) ...) *;{
push @xs, sum @xs[ max($len - $n, 0) .. $len-1 ];
nacci @starters[^$n];
}
@xs
}
 
say $_-1 . ': ' . join ' ', (fib_n $_)[0..19] for 2..10;
sub nacci (*@starter) {
say "\nLucas: " . join ' ', fib_n(2, [2,1], 20);</syntaxhighlight>
my &fun = EVAL join '+', '*' xx @starter;
@starter, &fun ... *;
}
 
for 2..10 -> $n { say fibo($n)[^20] }
say nacci(2,1)[^20];</lang>
{{out}}
<pre>1: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
2: 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 5768 10609 19513 35890 66012
3: 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 10671 20569 39648 76424 147312
4: 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 13624 26784 52656 103519 203513
5: 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 15109 29970 59448 117920 233904
6: 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 15808 31489 62725 124946 248888
7: 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 16128 32192 64256 128257 256005
8: 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 16272 32512 64960 129792 259328
9: 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 16336 32656 65280 130496 260864
2 1 3 4 7 11 18 29 47 76 123 199 322 521 843 1364 2207 3571 5778 9349</pre>
 
Lucas: 2 1 3 4 7 11 18 29 47 76 123 199 322 521 843 1364 2207 3571 5778 9349</pre>
===Generative===
A slightly more straight forward way of constructing a lazy list.
{{works with|Rakudo|2015.12}}
<lang perl6>sub fib ($n, @xs is copy = [1]) {
flat gather {
take @xs[*];
loop {
take my $x = [+] @xs;
@xs.push: $x;
@xs.shift if @xs > $n;
}
}
}
 
=={{header|Phix}}==
for 2..10 -> $n {
<!--<syntaxhighlight lang="phix">(phixonline)-->
say fib($n, [1])[^20];
<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>
say fib(2, [2,1])[^20];</lang>
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;"><</span><span style="color: #000000;">2</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">+</span><span style="color: #000000;">n</span><span style="color: #0000FF;">*</span><span style="color: #000000;">l</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
 
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #000000;">1</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
=={{header|PicoLisp}}==
<span style="color: #004080;">atom</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">nacci_noo</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</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>
<lang PicoLisp>(de nacci (Init Cnt)
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">min</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
(let N (length Init)
<span style="color: #000000;">res</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">nacci_noo</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">i</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>
(make
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
(made Init)
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
(do (- Cnt N)
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
(link (apply + (tail N (made)))) ) ) ) )</lang>
Test:
<span style="color: #008080;">constant</span> <span style="color: #000000;">names</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"lucas fibo tribo tetra penta hexa hepta octo nona deca"</span><span style="color: #0000FF;">)</span>
<lang PicoLisp># Fibonacci
<span style="color: #004080;">sequence</span> <span style="color: #000000;">f</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
: (nacci (1 1) 10)
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">4</span> <span style="color: #008080;">do</span>
-> (1 1 2 3 5 8 13 21 34 55)
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">10</span> <span style="color: #008080;">do</span>
 
<span style="color: #000000;">f</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">nacci_noo</span><span style="color: #0000FF;">(</span><span style="color: #000000;">j</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">),</span><span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
# Tribonacci
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
: (nacci (1 1 2) 10)
<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>
-> (1 1 2 4 7 13 24 44 81 149)
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
 
<!--</syntaxhighlight>-->
# Tetranacci
{{out}}
: (nacci (1 1 2 4) 10)
<pre>
-> (1 1 2 4 8 15 29 56 108 208)
lucasnacci: {2,1,3,4,7,11,18,29,47,76}
 
fibonacci: {1,1,2,3,5,8,13,21,34,55}
# Lucas
tribonacci: {1,1,2,4,7,13,24,44,81,149}
: (nacci (2 1) 10)
tetranacci: {1,1,2,4,8,15,29,56,108,208}
-> (2 1 3 4 7 11 18 29 47 76)
</pre>
 
# 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)</lang>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
/**
* @author Elad Yosifon
Line 2,300 ⟶ 3,761:
}
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,314 ⟶ 3,775:
DECANACCI => 1,1,2,4,8,16,32,64,128,256,512,1023,2045,4088,8172
</pre>
 
=={{header|PicoLisp}}==
<syntaxhighlight lang="picolisp">(de nacci (Init Cnt)
(let N (length Init)
(make
(made Init)
(do (- Cnt N)
(link (apply + (tail N (made)))) ) ) ) )</syntaxhighlight>
Test:
<syntaxhighlight lang="picolisp"># Fibonacci
: (nacci (1 1) 10)
-> (1 1 2 3 5 8 13 21 34 55)
 
# Tribonacci
: (nacci (1 1 2) 10)
-> (1 1 2 4 7 13 24 44 81 149)
 
# Tetranacci
: (nacci (1 1 2 4) 10)
-> (1 1 2 4 8 15 29 56 108 208)
 
# Lucas
: (nacci (2 1) 10)
-> (2 1 3 4 7 11 18 29 47 76)
 
# 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)</syntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">(subscriptrange, fixedoverflow, size):
n_step_Fibonacci: procedure options (main);
declare line character (100) varying;
Line 2,330 ⟶ 3,819:
get string (line || ' ') list ( n );
 
if n(1) = 2 then put ('We have a LucanLusas series');
else put ('We have a ' || trim(k) || '-step Fibonacci series.');
 
Line 2,343 ⟶ 3,832:
end;
end;
end n_step_Fibonacci;</langsyntaxhighlight>
Output:
<pre>
We have a LucanLucas series.
2 1 3 4 7 11 18 29 47 76 123 199 322 521 843 1364 2207 3571 5778 9349
 
Line 2,363 ⟶ 3,852:
 
=={{header|Powershell}}==
<langsyntaxhighlight Powershelllang="powershell">#Create generator of extended fibonaci
Function Get-ExtendedFibonaciGenerator($InitialValues ){
$Values = $InitialValues
Line 2,380 ⟶ 3,869:
}.GetNewClosure()
}
</syntaxhighlight>
</lang>
 
Example of invocation to generate up to decanaci
 
<langsyntaxhighlight Powershelllang="powershell">$Name = 'fibo tribo tetra penta hexa hepta octo nona deca'.Split()
0..($Name.Length-1) | foreach { $Index = $_
$InitialValues = @(1) + @(foreach ($I In 0..$Index) { [Math]::Pow(2,$I) })
Line 2,394 ⟶ 3,883:
}
} | Format-Table -AutoSize
</syntaxhighlight>
</lang>
Sample output
<pre>
Line 2,411 ⟶ 3,900:
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">
<lang PureBasic>
 
Procedure.i FibonacciLike(k,n=2,p.s="",d.s=".")
Line 2,468 ⟶ 3,957:
Debug ""
 
</syntaxhighlight>
</lang>
 
'''Sample Output'''
Line 2,490 ⟶ 3,979:
=={{header|Python}}==
===Python: function returning a function===
<langsyntaxhighlight lang="python">>>> def fiblike(start):
addnum = len(start)
memo = start[:]
Line 2,522 ⟶ 4,011:
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 ...
>>> </langsyntaxhighlight>
 
===Python: Callable class===
<langsyntaxhighlight lang="python">>>> class Fiblike():
def __init__(self, start):
self.addnum = len(start)
Line 2,558 ⟶ 4,047:
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 ...
>>> </langsyntaxhighlight>
 
===Python: Generator===
<langsyntaxhighlight lang="python">from itertools import islice, cycle
 
def fiblike(tail):
Line 2,579 ⟶ 4,068:
fib = fiblike([1] + [2 ** i for i in xrange(n - 1)])
items = list(islice(fib, 15))
print "n=%2i, %5snacci -> %s ..." % (n, name, items)</langsyntaxhighlight>
{{out}}
<pre>[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Line 2,592 ⟶ 4,081:
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] ...</pre>
 
===Python: Defined in terms of a generic anamorphism===
Defining the Lucas series and the N-Step Fibonacci series in terms of unfoldr (dual to functools.reduce).
{{Works with|Python|3.7}}
<syntaxhighlight lang="python">'''Fibonacci n-step number sequences'''
 
from itertools import chain, count, islice
 
 
# A000032 :: () -> [Int]
def A000032():
'''Non finite sequence of Lucas numbers.
'''
return unfoldr(recurrence(2))([2, 1])
 
 
# nStepFibonacci :: Int -> [Int]
def nStepFibonacci(n):
'''Non-finite series of N-step Fibonacci numbers,
defined by a recurrence relation.
'''
return unfoldr(recurrence(n))(
take(n)(
chain(
[1],
(2 ** i for i in count(0))
)
)
)
 
 
# recurrence :: Int -> [Int] -> Int
def recurrence(n):
'''Recurrence relation in Fibonacci and related series.
'''
def go(xs):
h, *t = xs
return h, t + [sum(take(n)(xs))]
return go
 
 
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''First 15 terms each n-step Fibonacci(n) series
where n is drawn from [2..8]
'''
labels = "fibo tribo tetra penta hexa hepta octo nona deca"
table = list(
chain(
[['lucas:'] + [
str(x) for x in take(15)(A000032())]
],
map(
lambda k, n: list(
chain(
[k + 'nacci:'],
(
str(x) for x
in take(15)(nStepFibonacci(n))
)
)
),
labels.split(),
count(2)
)
)
)
print('Recurrence relation series:\n')
print(
spacedTable(table)
)
 
 
# ----------------------- GENERIC ------------------------
 
# take :: Int -> [a] -> [a]
# take :: Int -> String -> String
def take(n):
'''The prefix of xs of length n,
or xs itself if n > length xs.
'''
def go(xs):
return (
xs[0:n]
if isinstance(xs, (list, tuple))
else list(islice(xs, n))
)
return go
 
 
# unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
def unfoldr(f):
'''Generic anamorphism.
A lazy (generator) list unfolded from a seed value by
repeated application of f until no residue remains.
Dual to fold/reduce.
f returns either None, or just (value, residue).
For a strict output value, wrap in list().
'''
def go(x):
valueResidue = f(x)
while None is not valueResidue:
yield valueResidue[0]
valueResidue = f(valueResidue[1])
return go
 
 
# ---------------------- FORMATTING ----------------------
 
# spacedTable :: [[String]] -> String
def spacedTable(rows):
columnWidths = [
max([len(x) for x in col])
for col in zip(*rows)
]
return '\n'.join([
' '.join(
map(
lambda x, w: x.rjust(w, ' '),
row, columnWidths
)
)
for row in rows
])
 
 
# MAIN ---
if __name__ == '__main__':
main()</syntaxhighlight>
{{Out}}
<pre>Recurrence relation series:
 
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
tribonacci: 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136
tetranacci: 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536
pentanacci: 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930
hexanacci: 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617
heptanacci: 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936
octonacci: 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080
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</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ 0 swap witheach + ] is sum ( [ --> n )
 
[ tuck size -
dup 0 < iff
[ split drop ]
else
[ dip [ dup size negate swap ]
times
[ over split
dup sum join join ]
nip ] ] is n-step ( n [ --> [ )
 
[ ' [ 1 1 ] n-step ] is fibonacci ( n --> [ )
 
[ ' [ 1 1 2 ] n-step ] is tribonacci ( n --> [ )
 
[ ' [ 1 1 2 4 ] n-step ] is tetranacci ( n --> [ )
 
[ ' [ 2 1 ] n-step ] is lucas ( n --> [ )
 
' [ fibonacci tribonacci tetranacci lucas ]
witheach
[ dup echo say ": " 10 swap do echo cr ]</syntaxhighlight>
 
{{out}}
 
<pre>fibonacci: [ 1 1 2 3 5 8 13 21 34 55 ]
tribonacci: [ 1 1 2 4 7 13 24 44 81 149 ]
tetranacci: [ 1 1 2 4 8 15 29 56 108 208 ]
lucas: [ 2 1 3 4 7 11 18 29 47 76 ]
</pre>
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
 
;; fib-list : [Listof Nat] x Nat -> [Listof Nat]
Line 2,618 ⟶ 4,284:
(cons 1 (build-list (sub1 n) (curry expt 2)))))
;; and with an initial (2 1)
(show-fibs "lucas" '(2 1))</langsyntaxhighlight>
 
{{out}}
Line 2,631 ⟶ 4,297:
decanacci: 1, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1023, 2045, 4088, 8172, 16336, 32656, 65280, 130496, 260864, ...
lucas: 2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322, 521, 843, 1364, 2207, 3571, 5778, 9349, ...</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
 
===Lazy List with Closure===
<syntaxhighlight lang="raku" line>sub nacci ( $s = 2, :@start = (1,) ) {
my @seq = |@start, { state $n = +@start; @seq[ ($n - $s .. $n++ - 1).grep: * >= 0 ].sum } … *;
}
 
put "{.fmt: '%2d'}-nacci: ", nacci($_)[^20] for 2..12 ;
 
put "Lucas: ", nacci(:start(2,1))[^20];</syntaxhighlight>
{{out}}
<pre> 2-nacci: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
3-nacci: 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 5768 10609 19513 35890 66012
4-nacci: 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 10671 20569 39648 76424 147312
5-nacci: 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 13624 26784 52656 103519 203513
6-nacci: 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 15109 29970 59448 117920 233904
7-nacci: 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 15808 31489 62725 124946 248888
8-nacci: 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 16128 32192 64256 128257 256005
9-nacci: 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 16272 32512 64960 129792 259328
10-nacci: 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 16336 32656 65280 130496 260864
11-nacci: 1 1 2 4 8 16 32 64 128 256 512 1024 2047 4093 8184 16364 32720 65424 130816 261568
12-nacci: 1 1 2 4 8 16 32 64 128 256 512 1024 2048 4095 8189 16376 32748 65488 130960 261888
Lucas: 2 1 3 4 7 11 18 29 47 76 123 199 322 521 843 1364 2207 3571 5778 9349</pre>
 
===Generative===
A slightly more straight forward way of constructing a lazy list.
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku" line>sub fib ($n, @xs is copy = [1]) {
flat gather {
take @xs[*];
loop {
take my $x = [+] @xs;
@xs.push: $x;
@xs.shift if @xs > $n;
}
}
}
 
for 2..10 -> $n {
say fib($n, [1])[^20];
}
say fib(2, [2,1])[^20];</syntaxhighlight>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program calculates and displays a N-step Fibonacci sequence(s). */
parse arg FibName values /*allows a Fibonacci name, starter vals*/
if FibName\='' then do; call nStepFib FibName,values; signal done; end
Line 2,667 ⟶ 4,377:
 
say right(Fname,11)'[sum'right(N,3) "terms]:" strip(L) '···'
return</langsyntaxhighlight>
'''output''' &nbsp; when using the default input:
<pre>
Line 2,683 ⟶ 4,393:
dodecanacci[sum 12 terms]: 1 1 2 4 8 16 32 64 128 256 512 1024 2048 4095 8189 16376 32748 65488 130960 261888 523712 1047296 2094336 4188160 8375296 16748544 33492993 66977797 133939218 267845688 ···
13th-order[sum 13 terms]: 1 1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8191 16381 32760 65516 131024 262032 524032 1048000 2095872 4191488 8382464 16763904 33525760 67047424 134086657 268156933 ···
</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Fibonacci n-step number sequences
 
f = list(12)
 
see "Fibonacci:" + nl
f2 = [1,1]
for nr2 = 1 to 10
see "" + f2[1] + " "
fibn(f2)
next
showarray(f2)
see " ..." + nl + nl
see "Tribonacci:" + nl
f3 = [1,1,2]
for nr3 = 1 to 9
see "" + f3[1] + " "
fibn(f3)
next
showarray(f3)
see " ..." + nl + nl
see "Tetranacci:" + nl
f4 = [1,1,2,4]
for nr4 = 1 to 8
see "" + f4[1] + " "
fibn(f4)
next
showarray(f4)
see " ..." + nl + nl
 
see "Lucas:" + nl
f5 = [2,1]
for nr5 = 1 to 10
see "" + f5[1] + " "
fibn(f5)
next
showarray(f5)
see " ..." + nl + nl
func fibn(fs)
s = sum(fs)
for i = 2 to len(fs)
fs[i-1] = fs[i]
next
fs[i-1] = s
return fs
 
func sum(arr)
sm = 0
for sn = 1 to len(arr)
sm = sm + arr[sn]
next
return sm
 
func showarray(fn)
svect = ""
for p = 1 to len(fn)
svect = svect + fn[p] + " "
next
see svect
</syntaxhighlight>
Output:
<pre>
Fibonacci:
1 1 2 3 5 8 13 21 34 55 89 144 ...
 
Tribonacci:
1 1 2 4 7 13 24 44 81 149 274 504 ...
 
Tetranacci:
1 1 2 4 8 15 29 56 108 208 401 773 ...
 
Lucas:
2 1 3 4 7 11 18 29 47 76 123 199 ...
</pre>
 
=={{header|RPL}}==
≪ OVER SIZE → len n
≪ LIST→
<span style="color:red">1</span> + len '''FOR''' j
n DUPN
<span style="color:red">2</span> n '''START''' + '''NEXT'''
'''NEXT''' len →LIST
≫ ≫ ‘<span style="color:blue">NFIB</span>’ STO
 
<span style="color:red">{1 1} 15</span> <span style="color:blue">NFIB</span>
DUP <span style="color:red">1 3</span> SUB <span style="color:red">15</span> <span style="color:blue">NFIB</span>
DUP <span style="color:red">1 4</span> SUB <span style="color:red">15</span> <span style="color:blue">NFIB</span>
<span style="color:red">{2 1} 15</span> <span style="color:blue">NFIB</span>
{{out}}
<pre>
4: { 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 }
3: { 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 }
2: { 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 }
1: { 2 1 3 4 7 11 18 29 47 76 123 199 322 521 843 }
</pre>
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">def anynacci(start_sequence, count)
{{works with|Ruby|1.9}}
n = start_sequence.length # Get the n-step for the type of fibonacci sequence
<lang ruby>def anynacci(start_sequence, count)
nresult = start_sequence.lengthdup # GetCreate a new result array with the n-stepvalues forcopied from the typearray that was ofpassed fibonacciby sequencereference
(count-n).times do # Loop for the remaining results up to count
result = start_sequence.dup # Create a new result array with the values copied from the array that was passed by reference
result << result.last(n).sum # Get the last n element from result and append its total to Array
(n+1..count).each do # Loop for the remaining results up to count
result << result.last(n).reduce(:+) # Get the last n element from result and append its total to Array
end
result
result # Return result
end
 
naccis = { lucuslucas: [2,1],
fibonacci: [1,1],
tribonacci: [1,1,2],
Line 2,709 ⟶ 4,516:
decanacci: [1,1,2,4,8,16,32,64,128,256] }
 
naccis.each {|name, seq| puts "%12s : %p" % [name, anynacci(seq, 15)]}</syntaxhighlight>
def print_nacci(naccis, count=15)
puts naccis.map {|name, seq| "%12s : %p" % [name, anynacci(seq, count)]}
end
 
print_nacci(naccis)</lang>
 
{{out}}
<langsyntaxhighlight lang="ruby"> lucuslucas : [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]
tribonacci : [1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, 927, 1705, 3136]
Line 2,726 ⟶ 4,528:
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>
</lang>
 
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">a = fib(" fibonacci ", "1,1")
{{incomplete|Run BASIC|Lucas?}}
<lang runbasic>a = fib("tribonacci ", "1,1,2")
a = fib("tetranacci ", "1,1,2,4")
a = fib(" pentanacc ", "1,1,2,4,8")
a = fib(" hexanacci ", "1,1,2,4,8,16")
a = fib("1,1 lucas ", "2,4,8,161")
 
function fib(f$, s$)
dim f(20)
while word$(fs$,b+1,",") <> ""
b = b + 1
f(b) = val(word$(fs$,b,","))
wend
PRINT "Fibonacci:";bf$; "=>";
for i = b to 13 + b
print " "; f(i-b+1); ",";
for j = (i - b) + 1 to i
f(i+1) = f(i+1) + f(j)
Line 2,750 ⟶ 4,552:
next i
print
end function</langsyntaxhighlight>
{{out}}
<pre>Fibonacci:2=>1,1,2,3,5,8,13,21,34,55,89,144,233,377,
Fibonacci:3<pre> fibonacci => 1, 1, 2,4 3,7 5,13 8,24 13,44 21,81 34,149 55,274 89,504 144,927 233,1705 377,
Fibonacci:4tribonacci => 1, 1, 2, 4,8 7,15 13,29 24,56 44,108 81,208 149,401 274,773 504,1490 927,2872 1705,
Fibonacci:5tetranacci => 1, 1, 2, 4, 8,16 15,31 29,61 56,120 108,236 208,464 401,912 773,1793 1490,3525 2872,
Fibonacci:6 pentanacc => 1, 1, 2, 4, 8, 16,32 31,63 61,125 120,248 236,492 464,976 912,1936 1793,3840 3525,</pre>
hexanacci => 1, 1, 2, 4, 8, 16, 32, 63, 125, 248, 492, 976, 1936, 3840,
lucas => 2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322, 521,</pre>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
struct GenFibonacci {
buf: Vec<u64>,
Line 2,800 ⟶ 4,604:
print(vec![2,1], 10 - 2);
}
</syntaxhighlight>
</lang>
 
<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>
</lang>
 
=={{header|Scala}}==
===Simple Solution===
<langsyntaxhighlight lang="scala">
//we rely on implicit conversion from Int to BigInt.
//BigInt is preferable since the numbers get very big, very fast.
//(though for a small example of the first few numbers it's not needed)
def fibStream(init: BigInt*): StreamLazyList[BigInt] = {
def inner(prev: Vector[BigInt]): StreamLazyList[BigInt] = prev.head #:: inner(prev.tail :+ prev.sum)
 
inner(init.toVector)
inner(init.toVector)
}
}
</lang>
</syntaxhighlight>
 
===Optimizing===
<langsyntaxhighlight lang="scala">
//in the optimized version we don't compute values until it's needed.
//the unoptimized version, computed k elements ahead, where k being
//the number of elements to sum (fibonacci: k=2, tribonacci: k=3, ...).
def fibStreamfib2Stream(init: BigInt*): StreamLazyList[BigInt] = {
def inner(prev: Vector[BigInt]): StreamLazyList[BigInt] = {
val sum = prev.sum
sum #:: inner(prev.tail :+ sum)
}
 
init.to(LazyList) #::: inner(init.toVector)
}
</syntaxhighlight>
init.toStream #::: inner(init.toVector)
}
</lang>
===Optimizing Further===
<langsyntaxhighlight lang="scala">
//instead of summing k elements each phase, we exploit the fact
//that the last element is already the sum of all k preceding elements
def fib2Streamfib3Stream(init: BigInt*): StreamLazyList[BigInt] = {
def inner(prev: Vector[BigInt]): StreamLazyList[BigInt] = {
val n = prev.last * 2 - prev.head
n #:: inner(prev.tail :+ n)
}
 
//last element must be the sum of k preceding elements, vector size should be k+1
val v = init.toVector :+ init.sum
v.to(LazyList) #::: inner(v)
}
</syntaxhighlight>
//last element must be the sum of k preceding elements, vector size should be k+1
val v = init.toVector :+ init.sum
v.toStream #::: inner(v)
}
</lang>
===Printing===
<langsyntaxhighlight lang="scala">
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>
</lang>
{{out}}
<pre>
Line 2,863 ⟶ 4,670:
</pre>
'''Note:''' In Scala, ''Stream'' is a lazy list. if you don't need the sequence saved in memory, just to iterate over members, you may convert the logic to use ''Iterator'' instead of ''Stream''.
 
=={{header|Scheme}}==
 
<syntaxhighlight lang="scheme">
(import (scheme base)
(scheme write)
(srfi 1))
 
;; uses n-step sequence formula to
;; continue lst until of length num
(define (n-fib lst num)
(let ((n (length lst)))
(do ((result (reverse lst)
(cons (fold + 0 (take result n))
result)))
((= num (length result)) (reverse result)))))
 
;; display examples
(do ((i 2 (+ 1 i)))
((> i 4) )
(display (string-append "n = "
(number->string i)
": "))
(display (n-fib (cons 1 (list-tabulate (- i 1) (lambda (n) (expt 2 n))))
15))
(newline))
 
(display "Lucas: ")
(display (n-fib '(2 1) 15))
(newline)
</syntaxhighlight>
 
{{out}}
<pre>
n = 2: (1 1 2 3 5 8 13 21 34 55 89 144 233 377 610)
n = 3: (1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136)
n = 4: (1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536)
Lucas: (2 1 3 4 7 11 18 29 47 76 123 199 322 521 843)
</pre>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func array integer: bonacci (in array integer: start, in integer: arity, in integer: length) is func
Line 2,901 ⟶ 4,747:
print("Tetranacci", bonacci([] (1, 1), 4, 10));
print("Lucas", bonacci([] (2, 1), 2, 10));
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,913 ⟶ 4,759:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func fib(n, xs=[1], k=20) {
loop {
var len = xs.len;
len >= 20k && break;
xs.append( << xs.ftslice(0.max(0, len - n)).sum);
}
return xs;
}
 
rangefor i in (2, ..10).each { |i|
say fib(i).join(' ');
}
say fib(2, [2, 1]).join(' ');</langsyntaxhighlight>
{{out}}
<pre>
Line 2,938 ⟶ 4,784:
1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 16336 32656 65280 130496 260864
2 1 3 4 7 11 18 29 47 76 123 199 322 521 843 1364 2207 3571 5778 9349
</pre>
 
Using matrix exponentiation:
<syntaxhighlight lang="ruby">func fibonacci_matrix(k) is cached {
Matrix.build(k,k, {|i,j|
((i == k-1) || (i == j-1)) ? 1 : 0
})
}
 
func fibonacci_kth_order(n, k=2) {
var A = fibonacci_matrix(k)
(A**n)[0][-1]
}
 
for k in (2..9) {
say ("Fibonacci of k=#{k} order: ", (15+k).of { fibonacci_kth_order(_, k) })
}</syntaxhighlight>
{{out}}
<pre>
Fibonacci of k=2 order: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]
Fibonacci of k=3 order: [0, 0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, 927, 1705, 3136, 5768]
Fibonacci of k=4 order: [0, 0, 0, 1, 1, 2, 4, 8, 15, 29, 56, 108, 208, 401, 773, 1490, 2872, 5536, 10671]
Fibonacci of k=5 order: [0, 0, 0, 0, 1, 1, 2, 4, 8, 16, 31, 61, 120, 236, 464, 912, 1793, 3525, 6930, 13624]
Fibonacci of k=6 order: [0, 0, 0, 0, 0, 1, 1, 2, 4, 8, 16, 32, 63, 125, 248, 492, 976, 1936, 3840, 7617, 15109]
Fibonacci of k=7 order: [0, 0, 0, 0, 0, 0, 1, 1, 2, 4, 8, 16, 32, 64, 127, 253, 504, 1004, 2000, 3984, 7936, 15808]
Fibonacci of k=8 order: [0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 4, 8, 16, 32, 64, 128, 255, 509, 1016, 2028, 4048, 8080, 16128]
Fibonacci of k=9 order: [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 4, 8, 16, 32, 64, 128, 256, 511, 1021, 2040, 4076, 8144, 16272]
</pre>
 
Faster algorithm:
<syntaxhighlight lang="ruby">func fibonacci_kth_order (n, k = 2) {
 
return 0 if (n < k-1)
 
var f = (1..(k+1) -> map {|j|
j < k ? 2**j : 1
})
 
k += 1
 
for i in (2*(k-1) .. n) {
f[i%k] = (2*f[(i-1)%k] - f[i%k])
}
 
return f[n%k]
}
 
for k in (2..9) {
say ("Fibonacci of k=#{k} order: ", (15+k).of { fibonacci_kth_order(_, k) })
}</syntaxhighlight>
(same output as above)
 
=={{header|Tailspin}}==
<syntaxhighlight lang="tailspin">
templates fibonacciNstep&{N:}
templates next
@: $(1);
$(2..last)... -> @: $ + $@;
[ $(2..last)..., $@ ] !
end next
 
@: $;
1..$N -> #
<>
$@(1) !
@: $@ -> next;
end fibonacciNstep
 
[1,1] -> fibonacciNstep&{N:10} -> '$; ' -> !OUT::write
'
' -> !OUT::write
 
[1,1,2] -> fibonacciNstep&{N:10} -> '$; ' -> !OUT::write
'
' -> !OUT::write
 
[1,1,2,4] -> fibonacciNstep&{N:10} -> '$; ' -> !OUT::write
'
' -> !OUT::write
 
[2,1] -> fibonacciNstep&{N:10} -> '$; ' -> !OUT::write
'
' -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
1 1 2 3 5 8 13 21 34 55
1 1 2 4 7 13 24 44 81 149
1 1 2 4 8 15 29 56 108 208
2 1 3 4 7 11 18 29 47 76
</pre>
 
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
proc fibber {args} {
Line 2,971 ⟶ 4,907:
print10 [fibber 1 1 2 4]
puts "LUCAS"
print10 [fibber 2 1]</langsyntaxhighlight>
{{out}}
<pre>
Line 2,983 ⟶ 4,919:
[2, 1, 3, 4, 7, 11, 18, 29, 47, 76, ...]
</pre>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">Option Explicit
 
Sub Main()
Dim temp$, T() As Long, i&
'Fibonacci:
T = Fibonacci_Step(1, 15, 1)
For i = LBound(T) To UBound(T)
temp = temp & ", " & T(i)
Next
Debug.Print "Fibonacci: " & Mid(temp, 3)
temp = ""
'Tribonacci:
T = Fibonacci_Step(1, 15, 2)
For i = LBound(T) To UBound(T)
temp = temp & ", " & T(i)
Next
Debug.Print "Tribonacci: " & Mid(temp, 3)
temp = ""
'Tetranacci:
T = Fibonacci_Step(1, 15, 3)
For i = LBound(T) To UBound(T)
temp = temp & ", " & T(i)
Next
Debug.Print "Tetranacci: " & Mid(temp, 3)
temp = ""
'Lucas:
T = Fibonacci_Step(1, 15, 1, 2)
For i = LBound(T) To UBound(T)
temp = temp & ", " & T(i)
Next
Debug.Print "Lucas: " & Mid(temp, 3)
temp = ""
End Sub
 
Private Function Fibonacci_Step(First As Long, Count As Long, S As Long, Optional Second As Long) As Long()
Dim T() As Long, R() As Long, i As Long, Su As Long, C As Long
 
If Second <> 0 Then S = 1
ReDim T(1 - S To Count)
For i = LBound(T) To 0
T(i) = 0
Next i
T(1) = IIf(Second <> 0, Second, 1)
T(2) = 1
For i = 3 To Count
Su = 0
C = S + 1
Do While C >= 0
Su = Su + T(i - C)
C = C - 1
Loop
T(i) = Su
Next
ReDim R(1 To Count)
For i = 1 To Count
R(i) = T(i)
Next
Fibonacci_Step = R
End Function</syntaxhighlight>
 
{{Out}}
<pre>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
Tetranacci: 1, 1, 2, 4, 8, 15, 29, 56, 108, 208, 401, 773, 1490, 2872, 5536
Lucas: 2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322, 521, 843</pre>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
'function arguments:
'init - initial series of the sequence(e.g. "1,1")
Line 3,017 ⟶ 5,023:
WScript.StdOut.Write "lucas: " & generate_seq("2,1",15)
WScript.StdOut.WriteLine
</syntaxhighlight>
</lang>
 
{{Out}}
Line 3,025 ⟶ 5,031:
tetranacci: 1,1,2,4,8,15,29,56,108,208,401,773,1490,2872,5536
lucas: 2,1,3,4,7,11,18,29,47,76,123,199,322,521,843
</pre>
 
=={{header|Visual Basic .NET}}==
{{trans|Visual Basic}}
{{works with|Visual Basic .NET|2011}}
<syntaxhighlight lang="vbnet">' Fibonacci n-step number sequences - VB.Net
Public Class FibonacciNstep
 
Const nmax = 20
 
Sub Main()
Dim bonacci As String() = {"", "", "Fibo", "tribo", "tetra", "penta", "hexa"}
Dim i As Integer
'Fibonacci:
For i = 2 To 6
Debug.Print(bonacci(i) & "nacci: " & FibonacciN(i, nmax))
Next i
'Lucas:
Debug.Print("Lucas: " & FibonacciN(2, nmax, 2))
End Sub 'Main
 
Private Function FibonacciN(iStep As Long, Count As Long, Optional First As Long = 0) As String
Dim i, j As Integer, Sigma As Long, c As String
Dim T(nmax) As Long
T(1) = IIf(First = 0, 1, First)
T(2) = 1
For i = 3 To Count
Sigma = 0
For j = i - 1 To i - iStep Step -1
If j > 0 Then
Sigma += T(j)
End If
Next j
T(i) = Sigma
Next i
c = ""
For i = 1 To nmax
c &= ", " & T(i)
Next i
Return Mid(c, 3)
End Function 'FibonacciN
 
End Class 'FibonacciNstep</syntaxhighlight>
{{out}}
<pre>
Fibonacci: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765
tribonacci: 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, 927, 1705, 3136, 5768, 10609, 19513, 35890, 66012
tetranacci: 1, 1, 2, 4, 8, 15, 29, 56, 108, 208, 401, 773, 1490, 2872, 5536, 10671, 20569, 39648, 76424, 147312
pentanacci: 1, 1, 2, 4, 8, 16, 31, 61, 120, 236, 464, 912, 1793, 3525, 6930, 13624, 26784, 52656, 103519, 203513
hexanacci: 1, 1, 2, 4, 8, 16, 32, 63, 125, 248, 492, 976, 1936, 3840, 7617, 15109, 29970, 59448, 117920, 233904
Lucas: 2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322, 521, 843, 1364, 2207, 3571, 5778, 9349
</pre>
 
=={{header|V (Vlang)}}==
{{trans|Wren}}
<syntaxhighlight lang="v (vlang)">fn fib_n(initial []int, num_terms int) []int {
n := initial.len
if n < 2 || num_terms < 0 {panic("Invalid argument(s).")}
if num_terms <= n {return initial}
mut fibs := []int{len:num_terms}
for i in 0..n {
fibs[i] = initial[i]
}
for i in n..num_terms {
mut sum := 0
for j in i-n..i {
sum = sum + fibs[j]
}
fibs[i] = sum
}
return fibs
}
 
fn main(){
names := [
"fibonacci", "tribonacci", "tetranacci", "pentanacci", "hexanacci",
"heptanacci", "octonacci", "nonanacci", "decanacci"
]
initial := [1, 1, 2, 4, 8, 16, 32, 64, 128, 256]
println(" n name values")
mut values := fib_n([2, 1], 15)
print(" 2 ${'lucas':-10}")
println(values.map('${it:4}').join(' '))
for i in 0..names.len {
values = fib_n(initial[0..i + 2], 15)
print("${i+2:2} ${names[i]:-10}")
println(values.map('${it:4}').join(' '))
}
}</syntaxhighlight>
 
{{out}}
<pre>
n name values
2 lucas 2 1 3 4 7 11 18 29 47 76 123 199 322 521 843
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
4 tetranacci 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536
5 pentanacci 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930
6 hexanacci 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617
7 heptanacci 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936
8 octonacci 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080
9 nonanacci 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144
10 decanacci 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172
</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./fmt" for Fmt
 
var fibN = Fn.new { |initial, numTerms|
var n = initial.count
if (n < 2 || numTerms < 0) Fiber.abort("Invalid argument(s).")
if (numTerms <= n) return initial.toList
var fibs = List.filled(numTerms, 0)
for (i in 0...n) fibs[i] = initial[i]
for (i in n...numTerms) {
var sum = 0
for (j in i-n...i) sum = sum + fibs[j]
fibs[i] = sum
}
return fibs
}
 
var names = [
"fibonacci", "tribonacci", "tetranacci", "pentanacci", "hexanacci",
"heptanacci", "octonacci", "nonanacci", "decanacci"
]
var initial = [1, 1, 2, 4, 8, 16, 32, 64, 128, 256]
System.print(" n name values")
var values = fibN.call([2, 1], 15)
Fmt.write("$2d $-10s", 2, "lucas")
Fmt.aprint(values, 4, 0, "")
for (i in 0..8) {
values = fibN.call(initial[0...i + 2], 15)
Fmt.write("$2d $-10s", i + 2, names[i])
Fmt.aprint(values, 4, 0, "")
}</syntaxhighlight>
 
{{out}}
<pre>
n name values
2 lucas 2 1 3 4 7 11 18 29 47 76 123 199 322 521 843
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
4 tetranacci 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536
5 pentanacci 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930
6 hexanacci 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617
7 heptanacci 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936
8 octonacci 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080
9 nonanacci 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144
10 decanacci 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
 
proc Nacci(N, F0); \Generate Fibonacci N-step sequence
Line 3,050 ⟶ 5,208:
Text(0, "Tetranacci: "); Nacci(4, [1, 1, 2, 4]);
Text(0, " Lucas: "); Nacci(2, [2, 1]);
]</langsyntaxhighlight>
 
Output:
Line 3,059 ⟶ 5,217:
Lucas: 2 1 3 4 7 11 18 29 47 76
</pre>
 
=={{header|Yabasic}}==
{{trans|Lua}}
<syntaxhighlight lang="yabasic">sub nStepFibs$(seq$, limit)
local iMax, sum, numb$(1), lim, i
lim = token(seq$, numb$(), ",")
redim numb$(limit)
seq$ = ""
iMax = lim - 1
while(lim < limit)
sum = 0
for i = 0 to iMax : sum = sum + val(numb$(lim - i)) : next
lim = lim + 1
numb$(lim) = str$(sum)
wend
for i = 0 to lim : seq$ = seq$ + " " + numb$(i) : next
return seq$
end sub
 
print "Fibonacci:", nStepFibs$("1,1", 10)
print "Tribonacci:", nStepFibs$("1,1,2", 10)
print "Tetranacci:", nStepFibs$("1,1,2,4", 10)
print "Lucas:", nStepFibs$("2,1", 10)</syntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn fibN(ns){ fcn(ns){ ns.append(ns.sum()).pop(0) }.fp(vm.arglist.copy()); }</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="zkl">N:=15;
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 3,069 ⟶ 5,251:
"%2d: ".fmt(ns.len()).print();
(N).pump(List,fibN(ns.xplode())).println();
}</langsyntaxhighlight>
{{out}}
<pre>
2,130

edits