Fibonacci n-step number sequences: Difference between revisions
Added various BASIC dialects (Chipmunk Basic, QBasic, and QB64)
m (Add awk solution) |
(Added various BASIC dialects (Chipmunk Basic, QBasic, and QB64)) |
||
(72 intermediate revisions by 28 users not shown) | |||
Line 52:
;Also see:
* [https://www.youtube.com/watch?v=PeUbRXnbmms Lucas Numbers - Numberphile] (Video)
* [https://www.youtube.com/watch?v=fMJflV_GUpU Tribonacci Numbers (and the Rauzy Fractal) - Numberphile] (Video)
* [[wp:Lucas number|Wikipedia, Lucas number]]
* [http://mathworld.wolfram.com/FibonacciNumber.html MathWorld, Fibonacci Number]
* [http://www.math-cs.ucmo.edu/~curtisc/articles/howardcooper/genfib4.pdf Some identities for r-Fibonacci numbers]
* [[oeis:A000045|OEIS Fibonacci numbers]]
* [[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>> (n-bonacci '(1 1) 10)
(1 2 3 5 8 13 21 34 55 89)
> (n-bonacci '(1 1 2) 10)
(1 2 4 7 13 24 44 81 149 274)
> (n-bonacci '(1 1 2 4) 10)
(1 2 4 8 15 29 56 108 208 401)
> (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 58 ⟶ 323:
First, we specify a package Bonacci, that defines the type Sequence (of Positive numbers), a function Generate that takes a given Start sequence and outputs a generalized N-Bonacci Sequence of a spefified Length, and some constant start sequences.
<
type Sequence is array(Positive range <>) of Positive;
Line 68 ⟶ 333:
Start_Tetranacci: constant Sequence := (1, 1, 2, 4);
Start_Lucas: constant Sequence := (2, 1);
end Bonacci;</
The implementation is quite straightforward.
<
function Generate(Start: Sequence; Length: Positive := 10) return Sequence is
Line 91 ⟶ 356:
end Generate;
end Bonacci;</
Finally, we actually generate some sequences, as required by the task. For convenience, we define a procedure Print that outputs a sequence,
<
procedure Test_Bonacci is
Line 115 ⟶ 380:
Print("Decanacci: ",
Bonacci.Generate((1, 1, 2, 4, 8, 16, 32, 64, 128, 256), 15));
end Test_Bonacci;</
The output:
Line 124 ⟶ 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|ALGOL 68}}==
<
# the initial values are taken from the init array #
PROC n step fibonacci sequence = ( []INT init, INT required count )[]INT:
Line 181 ⟶ 421:
print sequence( "tetrabonacci", n step fibonacci sequence( ( 1, 1, 2, 4 ), 10 ) );
print sequence( "lucus ", n step fibonacci sequence( ( 2, 1 ), 10 ) )
</syntaxhighlight>
{{out}}
<pre>
Line 189 ⟶ 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
Line 435 ⟶ 687:
end tell
end zipWith
</syntaxhighlight>
{{Out}}
<pre>Lucas -> [2,1,3,4,7,11,18,29,47,76,123,199,322,521,843]
Line 447 ⟶ 699:
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}}==
<
Loop, 9 {
Out .= seq "(" A_Index + 1 "): "
Line 465 ⟶ 816:
}
return, a
}</
'''Output:'''
<pre>nacci(2): 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610
Line 487 ⟶ 838:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
function sequence(values, howmany) {
init_length = length(values)
Line 518 ⟶ 869:
print("lucas :\t\t",sequence(a, 10))
}
</syntaxhighlight>
'''Output:'''
<pre>
Line 526 ⟶ 877:
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}}==
<
@echo off
Line 577 ⟶ 1,112:
endlocal
exit /b
</syntaxhighlight>
{{out}}
<pre>
Line 592 ⟶ 1,127:
2 1 | 3 4 7 11 18 29 47 76 123 199
</pre>
=={{header|BBC BASIC}}==
The BBC BASIC '''SUM''' function is useful here.
<
PRINT "Fibonacci:"
Line 622 ⟶ 1,156:
NEXT
f%(i%-1) = s%
ENDPROC</
'''Output:'''
<pre>
Line 637 ⟶ 1,171:
=={{header|Befunge}}==
<
v9013"Tetranacci"9014"Lucas"<
>"iccanobirT"2109"iccanobiF"v
Line 644 ⟶ 1,178:
_$.1+:77+`^vg03:_0g+>\:1+#^
50p-\30v v\<>\30g1-\^$$_:1-
05g04\g< >`#^_:40p30g0>^!:g</
{{out}}
Line 656 ⟶ 1,190:
=={{header|Bracmat}}==
{{trans|PicoLisp}}
<
= Init Cnt N made tail
. ( plus
Line 696 ⟶ 1,230:
& out$(str$(pad$!name ": ") nacci$(!Init.12))
)
);</
Output:
<pre> fibonacci: 1 1 2 3 5 8 13 21 34 55 89 144
Line 708 ⟶ 1,242:
decanacci: 1 1 2 4 8 16 32 64 128 256 512 1023
lucas: 2 1 3 4 7 11 18 29 47 76 123 199</pre>
=={{header|BQN}}==
<syntaxhighlight lang="bqn">NStep ← ⊑(1↓⊢∾+´)∘⊢⍟⊣
Nacci ← (2⋆0∾↕)∘(⊢-1˙)
>((↕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}}==
<
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 752 ⟶ 1,299:
return 0;
}</
Output:
Line 769 ⟶ 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++}}==
<
#include <iostream>
#include <numeric>
Line 820 ⟶ 1,457:
}
return 0 ;
}</
Output:
<pre>fibonacci : 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
Line 845 ⟶ 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.
<
#include <iostream>
#include <vector>
Line 911 ⟶ 1,548:
}
}
</syntaxhighlight>
=={{header|Clojure}}==
<
(letfn [(s [] (lazy-cat init (apply map + (map #(drop % (s)) (range (count init))))))]
(s)))
Line 1,012 ⟶ 1,559:
(show "Tribonacci" [1 1 2])
(show "Tetranacci" [1 1 2 4])
(show "Lucas" [2 1]))</
{{out}}
<pre>first 20 Fibonacci (1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765)
Line 1,019 ⟶ 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}}==
<
(defun gen-fib (lst m)
"Return the first m members of a generalized Fibonacci sequence using lst as initial values
Line 1,039 ⟶ 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))))</
{{out}}
<pre>Lucas series: (2 1 3 4 7 11 18 29 47 76)
Line 1,045 ⟶ 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===
<
import std.stdio, std.algorithm, std.range, std.conv;
Line 1,075 ⟶ 1,676:
15.iota.map!fibber);
}
}</
{{out}}
<pre>[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Line 1,091 ⟶ 1,692:
===Callable Struct===
The output is similar.
<
struct fiblike(T) {
Line 1,125 ⟶ 1,726:
n, name, 15.iota.map!fib);
}
}</
===Struct With opApply===
The output is similar.
<
struct Fiblike(T) {
Line 1,172 ⟶ 1,773:
writefln("n=%2d, %5snacci -> %s", n, name, fib.takeApply(15));
}
}</
===Range Generator Version===
<
import std.stdio, std.algorithm, std.range, std.concurrency;
Line 1,193 ⟶ 1,794:
writefln("n=%2d, %5snacci -> %(%s, %), ...", n, name, fib.take(15));
}
}</
{{out}}
<pre>[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Line 1,206 ⟶ 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}}==
<
;; generate a recursive lambda() for a x-nacci
;; equip it with memoïzation
Line 1,232 ⟶ 1,863:
(make-nacci name seed)
(printf "%s[%d] → %d" name (vector-length seed) (take name 16))))
</syntaxhighlight>
{{out}}
Line 1,248 ⟶ 1,879:
=={{header|Elixir}}==
{{trans|Ruby}}
<
def anynacci(start_sequence, count) do
n = length(start_sequence)
Line 1,276 ⟶ 1,907:
:io.format("~11s: ", [name])
IO.inspect RC.anynacci(list, 15)
end)</
{{out}}
Line 1,293 ⟶ 1,924:
=={{header|Erlang}}==
<syntaxhighlight lang="text">
-module( fibonacci_nstep ).
Line 1,315 ⟶ 1,946:
{Sum_ns, _Not_sum_ns} = lists:split( Nth, Ns ),
{Nth, [lists:sum(Sum_ns) | Ns]}.
</syntaxhighlight>
{{out}}
<pre>
Line 1,326 ⟶ 1,957:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM FIBON
Line 1,370 ⟶ 2,001:
FIB("Lucas","2,1")
END PROGRAM
</syntaxhighlight>
=={{header|F_Sharp|F#}}==
<
let fiblike init =
Line 1,396 ⟶ 2,027:
(Seq.init prefix.Length (fun i -> (prefix.[i], i+2)))
printfn " lucas -> %A" (start (fiblike [2; 1]))
0</
Output
<pre>n= 2, fibonacci -> [1; 1; 2; 3; 5; 8; 13; 21; 34; 55; 89; 144; 233; 377; 610]
Line 1,411 ⟶ 2,042:
=={{header|Factor}}==
<code>building</code> is a dynamic variable that refers to the sequence being built by <code>make</code>. This is useful when the next element of the sequence depends on previous elements.
<
: n-bonacci ( n initial -- seq ) [
Line 1,420 ⟶ 2,051:
qw{ fibonacci tribonacci tetranacci lucas }
{ { 1 1 } { 1 1 2 } { 1 1 2 4 } { 2 1 } }
[ 10 swap n-bonacci "%-10s %[%3d, %]\n" printf ] 2each</
{{out}}
<pre>
Line 1,428 ⟶ 2,059:
lucas { 2, 1, 3, 4, 7, 11, 18, 29, 47, 76 }
</pre>
=={{header|Forth}}==
<
: a{ here cell allot ;
: } , here over - cell / over ! ;
Line 1,462 ⟶ 2,085:
." tetranacci: " a{ 1 , 1 , 2 , 4 } show-nacci
." lucas: " a{ 2 , 1 } show-nacci
</syntaxhighlight>
{{out}}
<pre>fibonacci: 1 1 2 3 5 8 13 21 34 55
Line 1,471 ⟶ 2,094:
=={{header|Fortran}}==
<
! save this program as file f.f08
! gnu-linux command to build and test
Line 1,536 ⟶ 2,159:
end subroutine nacci
end program f
</syntaxhighlight>
<pre>
Line 1,578 ⟶ 2,201:
=={{header|FreeBASIC}}==
<
' Deduces the step, n, from the length of the dynamic array passed in
Line 1,628 ⟶ 2,251:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,639 ⟶ 2,262:
=={{header|FunL}}==
<
native scala.collection.mutable.Queue
Line 1,669 ⟶ 2,292:
t.row( ([k] + [seqs(i)(k) | i <- 0:4]).toIndexedSeq() )
print( t )</
{{out}}
Line 1,689 ⟶ 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 separate goroutines.
<
import "fmt"
Line 1,730 ⟶ 2,415:
fmt.Println()
}
}</
{{out}}
<pre>
Line 1,741 ⟶ 2,426:
=={{header|Groovy}}==
=====Solution=====
<
assert seed : "The seed list must be non-null and non-empty"
assert seed.every { it instanceof Number } : "Every member of the seed must be a number"
Line 1,754 ⟶ 2,439:
}
}
}</
=====Test=====
<
' fibonacci':[1,1],
'tribonacci':[1,1,2],
Line 1,772 ⟶ 2,457:
println " lucas[0]: ${fib([2,1],0)}"
println " tetra[3]: ${fib([1,1,2,4],3)}"</
{{out}}
<pre> fibonacci: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Line 1,788 ⟶ 2,473:
=={{header|Haskell}}==
<
import
fiblike :: [Integer] -> [Integer]
fiblike st = xs
where
xs = st <> map (sum . take n) (tails xs)
n = length st
nstep :: Int -> [Integer]
nstep n = fiblike $ take n $ 1 : iterate (2 *) 1
main :: IO ()
main = do
mapM_ (print
zipWithM_
putStr (name <> "nacci -> ")
print $ take 15 $ nstep n
)
[2 ..]
(words "fibo tribo tetra penta hexa hepta octo nona deca")</syntaxhighlight>
{{out}}
<pre>
Line 1,822 ⟶ 2,511:
Or alternatively, without imports – using only the default Prelude:
<syntaxhighlight lang="haskell">------------ FIBONACCI N-STEP NUMBER SEQUENCES -----------
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
<> ("-> "
)
"fibo tribo tetra penta hexa hepta octo nona deca"
)
[2 ..]
)
justifyLeft :: Int -> Char -> String -> String
justifyLeft n c s = take n (s
<pre>Lucas -> [2,1,3,4,7,11,18,29,47,76,123,199,322,521,843]
fibonaccci -> [1,1,2,3,5,8,13,21,34,55,89,144,233,377,610]
Line 1,856 ⟶ 2,554:
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:
<
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,874 ⟶ 2,646:
suspend cache[i]
}
end</
Output:
Line 1,889 ⟶ 2,661:
A slightly longer version of <tt>fnsGen</tt> that reduces the memory
footprint is:
<
every i := seq() do {
if i := (i > *cache, *cache) then {
Line 1,898 ⟶ 2,670:
suspend cache[i]
}
end</
The output is identical.
Line 1,904 ⟶ 2,676:
=={{header|J}}==
'''Solution''':<
'''Example''' ''(Lucas)'':<
2 1 3 4 7 11 18 29 47 76</
'''Example''' ''(extended 'nacci series)'':<
2 fibonacci 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
3 tribonacci 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
Line 1,929 ⟶ 2,701:
octonacci ✓
nonanacci ✓
decanacci ✓</
=={{header|Java}}==
Line 1,935 ⟶ 2,707:
'''Code:'''
<
{
public static int[] lucas(int n, int numRequested)
Line 1,979 ⟶ 2,751:
}
}
}</
Output:
Line 2,000 ⟶ 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===
<
return nacci(nacci([1,1], arity, arity), arity, len);
}
Line 2,029 ⟶ 2,800:
}
main();</
{{out}}
<pre>fib(2): 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610
Line 2,051 ⟶ 2,822:
===ES6===
<
'use strict';
Line 2,164 ⟶ 2,935:
// MAIN ---
return main();
})();</
<pre>Lucas -> [2,1,3,4,7,11,18,29,47,76,123,199,322,521,843]
fibonacci -> [1,1,2,3,5,8,13,21,34,55,89,144,233,377,610]
Line 2,178 ⟶ 2,949:
=={{header|jq}}==
{{Works with|jq|1.4}}
<
def nacci(arity; len):
arity as $arity | len as $len
Line 2,192 ⟶ 2,963:
def lucas(arity; len):
arity as $arity | len as $len
| [2,1] | nacci($arity; $arity) | nacci($arity; $len) ;</
'''Example''':
<
(range(2; 11) | "fib(\(.)): \(fib(.; 15))"),
(range(2; 11) | "lucas(\(.)): \(lucas(.; 15))")
;
main</
{{Out}}
$ jq -M -r -n -f fibonacci_n-step.jq
Line 2,210 ⟶ 2,981:
'''Generalized Fibonacci Iterator Definition'''
<syntaxhighlight lang="julia">
type NFib{T<:Integer}
n::T
Line 2,241 ⟶ 3,012:
return (f, fs)
end
</syntaxhighlight>
'''Specification of the n-step Fibonacci Iterator'''
The seeding for this series of sequences is <math>F_{1-n} = 1</math> and <math>F_{2-n} \ldots F_{0}=0</math>.
<syntaxhighlight lang="julia">
function fib_seeder{T<:Integer}(n::T)
a = zeros(BigInt, n)
Line 2,256 ⟶ 3,027:
NFib(n, k, fib_seeder)
end
</syntaxhighlight>
'''Specification of the Rosetta Code n-step Lucas Iterator'''
This iterator produces the task description's version of the Lucas Sequence ([https://oeis.org/A000032 OEIS A000032]) and its generalization to n-steps as was done by some of the other solutions to this task. The seeding for this series of sequences is <math>F_{1-n} = 3</math>, <math>F_{2-n} = -1</math> and, for <math>n > 2</math>, <math>F_{3-n} \ldots F_{0}=0</math>.
<syntaxhighlight lang="julia">
function luc_rc_seeder{T<:Integer}(n::T)
a = zeros(BigInt, n)
Line 2,272 ⟶ 3,043:
NFib(n, k, luc_rc_seeder)
end
</syntaxhighlight>
'''Specification of the MathWorld n-step Lucas Iterator'''
This iterator produces the Mathworld version of the Lucas Sequence ([http://mathworld.wolfram.com/LucasNumber.html Lucas Number] and [https://oeis.org/A000204 OEIS A000204]) and its generalization to n-steps according to Mathworld ([http://mathworld.wolfram.com/Lucasn-StepNumber.html Lucas n-Step Number] and [https://cs.uwaterloo.ca/journals/JIS/VOL8/Noe/noe5.html Primes in Fibonacci n-step and Lucas n-step Sequences]). The seeding for this series of sequences is <math>F_{0} = n</math> and <math>F_{1-n} \ldots F_{-1}=-1</math>.
<syntaxhighlight lang="julia">
function luc_seeder{T<:Integer}(n::T)
a = -ones(BigInt, n)
Line 2,287 ⟶ 3,058:
NFib(n, k, luc_seeder)
end
</syntaxhighlight>
'''Main'''
<syntaxhighlight lang="julia">
lo = 2
hi = 10
Line 2,326 ⟶ 3,097:
println()
end
</syntaxhighlight>
{{out}}
Line 2,365 ⟶ 3,136:
=={{header|Kotlin}}==
<
fun fibN(initial: IntArray, numTerms: Int) : IntArray {
Line 2,391 ⟶ 3,162:
println("%2d %-10s %s".format(i + 2, names[i], values))
}
}</
{{out}}
Line 2,409 ⟶ 3,180:
=={{header|Lua}}==
<
local iMax, sum = #seq - 1
while #seq < limit do
Line 2,428 ⟶ 3,199:
io.write(sequence.name .. ": ")
print(table.concat(nStepFibs(sequence.values, 10), " "))
end</
{{out}}
<pre>Fibonacci: 1 1 2 3 5 8 13 21 34 55
Line 2,436 ⟶ 3,207:
=={{header|Maple}}==
<
local n, i, values;
n := numelems(initValues);
Line 2,451 ⟶ 3,222:
printf ("nacci(%d): %a\n", i, convert(numSequence(initValues), list));
end do:
printf ("lucas: %a\n", convert(numSequence(Array([2, 1])), list));</
{{out}}
<pre>
Line 2,467 ⟶ 3,238:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">
f2=Function[{l,k},
Module[{n=Length@l,m},
Line 2,474 ⟶ 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>
Output:
<pre>
Line 2,501 ⟶ 3,272:
=={{header|Nim}}==
{{trans|Python}}
<
proc fiblike(start: seq[int]): auto =
Line 2,510 ⟶ 3,281:
else:
var ans = 0
for i in n-start.len ..
ans += fibber(i)
memo.add ans
Line 2,527 ⟶ 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>
Output:
<pre>@[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Line 2,545 ⟶ 3,315:
We will use lazy lists, so can get any amount of n-nacci numbers.
<
(define (n-fib-iterator ll)
(cons (car ll)
(lambda ()
(n-fib-iterator (append (cdr ll) (list (fold + 0 ll)))))))
</syntaxhighlight>
Testing:
<
(print "2, fibonacci : " (ltake (n-fib-iterator '(1 1)) 15))
(print "3, tribonacci: " (ltake (n-fib-iterator '(1 1 2)) 15))
Line 2,566 ⟶ 3,336:
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 2,572 ⟶ 3,342:
Use genV if you prefer to supply a different starting vector.
<
genV(n)=v->for(i=3,min(#v,n),v[i]=2^(i-2));for(i=n+1,#v,v[i]=sum(j=i-n,i-1,v[j]));v
for(n=2,10,print(n"\t"gen(n)(10)))</
{{out}}
<pre>2 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Line 2,588 ⟶ 3,358:
=={{header|Pascal}}==
{{works with|Free_Pascal}}
<
type
Line 2,657 ⟶ 3,427:
write(sequence[k], ' ');
writeln;
end.</
Output:
<pre>% ./Fibbonacci
Line 2,678 ⟶ 3,448:
Fib(n)/Fib(n-1) tends to the golden ratio = 1.618... 1.618^100 > 2^64
{{works with|Free_Pascal}}
<
program FibbonacciN (output);
{$IFNDEF FPC}
Line 2,791 ⟶ 3,561:
write(NextNacci(Nacci),' ');
writeln;
END.</
=={{header|
===Unfold===
I first define a high order function to generate infinite sequences given a lambda and a seed.
<syntaxhighlight lang="pascal">
// unfold infinite sequences. Nigel Galloway: September 8th., 2022
function unfold<gN,gG>(n:Func<gG,(gN,gG)>; g:gG): sequence of gN;
begin
var (x,r):=n(g);
yield x;
yield sequence unfold(n,r);
end;
function unfold<gN,gG>(n:Func<array of gG,(gN,array of gG)>;params g:array of gG): sequence of gN := unfold(n,g);
</syntaxhighlight>
===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>
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,829 ⟶ 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>
=={{header|Perl
<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) {
my @xs = @$xs;
while ( $max > (my $len = @xs) ) {
push @xs, sum @xs[ max($len - $n, 0) .. $len-1 ];
}
@xs
}
say $_-1 . ': ' . join ' ', (fib_n $_)[0..19] for 2..10;
say
{{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
Lucas: 2 1 3 4 7 11 18 29 47 76 123 199 322 521 843 1364 2207 3571 5778 9349</pre>
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<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>
<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>
<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>
<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>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<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>
<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>
<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>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%snacci: %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">names</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">f</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,906 ⟶ 3,680:
=={{header|PHP}}==
<
/**
* @author Elad Yosifon
Line 2,987 ⟶ 3,761:
}
</syntaxhighlight>
{{out}}
<pre>
Line 3,003 ⟶ 3,777:
=={{header|PicoLisp}}==
<
(let N (length Init)
(make
(made Init)
(do (- Cnt N)
(link (apply + (tail N (made)))) ) ) ) )</
Test:
<
: (nacci (1 1) 10)
-> (1 1 2 3 5 8 13 21 34 55)
Line 3,028 ⟶ 3,802:
# Decanacci
: (nacci (1 1 2 4 8 16 32 64 128 256) 15)
-> (1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172)</
=={{header|PL/I}}==
<
n_step_Fibonacci: procedure options (main);
declare line character (100) varying;
Line 3,045 ⟶ 3,819:
get string (line || ' ') list ( n );
if n(1) = 2 then put ('We have a
else put ('We have a ' || trim(k) || '-step Fibonacci series.');
Line 3,058 ⟶ 3,832:
end;
end;
end n_step_Fibonacci;</
Output:
<pre>
We have a
2 1 3 4 7 11 18 29 47 76 123 199 322 521 843 1364 2207 3571 5778 9349
Line 3,078 ⟶ 3,852:
=={{header|Powershell}}==
<
Function Get-ExtendedFibonaciGenerator($InitialValues ){
$Values = $InitialValues
Line 3,095 ⟶ 3,869:
}.GetNewClosure()
}
</syntaxhighlight>
Example of invocation to generate up to decanaci
<
0..($Name.Length-1) | foreach { $Index = $_
$InitialValues = @(1) + @(foreach ($I In 0..$Index) { [Math]::Pow(2,$I) })
Line 3,109 ⟶ 3,883:
}
} | Format-Table -AutoSize
</syntaxhighlight>
Sample output
<pre>
Line 3,126 ⟶ 3,900:
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">
Procedure.i FibonacciLike(k,n=2,p.s="",d.s=".")
Line 3,183 ⟶ 3,957:
Debug ""
</syntaxhighlight>
'''Sample Output'''
Line 3,205 ⟶ 3,979:
=={{header|Python}}==
===Python: function returning a function===
<
addnum = len(start)
memo = start[:]
Line 3,237 ⟶ 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 ...
>>> </
===Python: Callable class===
<
def __init__(self, start):
self.addnum = len(start)
Line 3,273 ⟶ 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 ...
>>> </
===Python: Generator===
<
def fiblike(tail):
Line 3,294 ⟶ 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)</
{{out}}
<pre>[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Line 3,308 ⟶ 4,082:
n=10, decanacci -> [1, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1023, 2045, 4088, 8172] ...</pre>
===Python:
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
'''
return
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 -> 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
#
def
'''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}}
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
</pre>
=={{header|Racket}}==
<
;; fib-list : [Listof Nat] x Nat -> [Listof Nat]
Line 3,474 ⟶ 4,284:
(cons 1 (build-list (sub1 n) (curry expt 2)))))
;; and with an initial (2 1)
(show-fibs "lucas" '(2 1))</
{{out}}
Line 3,487 ⟶ 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}}==
<
parse arg FibName values /*allows a Fibonacci name, starter vals*/
if FibName\='' then do; call nStepFib FibName,values; signal done; end
Line 3,523 ⟶ 4,377:
say right(Fname,11)'[sum'right(N,3) "terms]:" strip(L) '···'
return</
'''output''' when using the default input:
<pre>
Line 3,542 ⟶ 4,396:
=={{header|Ring}}==
<
# Project : Fibonacci n-step number sequences
Line 3,604 ⟶ 4,458:
next
see svect
</syntaxhighlight>
Output:
<pre>
Line 3,618 ⟶ 4,472:
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)
n = start_sequence.length # Get the n-step for the type of fibonacci sequence
(count-n).times do # Loop for the remaining results up to count
result << result.last(n).sum # Get the last n element from result and append its total to Array
end
result
end
naccis = {
fibonacci: [1,1],
tribonacci: [1,1,2],
Line 3,644 ⟶ 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>
{{out}}
<
fibonacci : [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
tribonacci : [1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, 927, 1705, 3136]
Line 3,661 ⟶ 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>
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">a = fib(" fibonacci ", "1,1")
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("
function fib(f$, s$)
dim f(20)
while word$(
b
f(b)
wend
PRINT
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 3,685 ⟶ 4,552:
next i
print
end function</
{{out}}
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}}==
<
struct GenFibonacci {
buf: Vec<u64>,
Line 3,735 ⟶ 4,604:
print(vec![2,1], 10 - 2);
}
</syntaxhighlight>
<syntaxhighlight lang="text">
Fib2: 1 1 2 3 5 8 13 21 34 55
Fib3: 1 1 2 4 7 13 24 44 81 149
Fib4: 1 1 2 4 8 15 29 56 108 208
Lucas: 2 1 3 4 7 11 18 29 47 76
</syntaxhighlight>
=={{header|Scala}}==
===Simple Solution===
<
//we rely on implicit conversion from Int to BigInt.
//BigInt is preferable since the numbers get very big, very fast.
//(though for a small example of the first few numbers it's not needed)
def fibStream(init: BigInt*):
def inner(prev: Vector[BigInt]):
inner(init.toVector)
}
</syntaxhighlight>
===Optimizing===
<
//in the optimized version we don't compute values until it's needed.
//the unoptimized version, computed k elements ahead, where k being
//the number of elements to sum (fibonacci: k=2, tribonacci: k=3, ...).
def
def inner(prev: Vector[BigInt]):
val sum = prev.sum
sum #:: inner(prev.tail :+ sum)
}
init.to(LazyList) #::: inner(init.toVector)
}
</syntaxhighlight>
===Optimizing Further===
<
//instead of summing k elements each phase, we exploit the fact
//that the last element is already the sum of all k preceding elements
def
def inner(prev: Vector[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>
===Printing===
<
println(s"Fibonacci: ${fibStream(1,1).take(10).mkString(",")}")
println(s"Tribonacci: ${fibStream(1,1,2).take(10).mkString(",")}")
println(s"Tetranacci: ${fibStream(1,1,2,4).take(10).mkString(",")}")
println(s"Lucas: ${fibStream(2,1).take(10).mkString(",")}")
</syntaxhighlight>
{{out}}
<pre>
Line 3,801 ⟶ 4,673:
=={{header|Scheme}}==
<
(import (scheme base)
(scheme write)
Line 3,828 ⟶ 4,700:
(display (n-fib '(2 1) 15))
(newline)
</syntaxhighlight>
{{out}}
Line 3,839 ⟶ 4,711:
=={{header|Seed7}}==
<
const func array integer: bonacci (in array integer: start, in integer: arity, in integer: length) is func
Line 3,875 ⟶ 4,747:
print("Tetranacci", bonacci([] (1, 1), 4, 10));
print("Lucas", bonacci([] (2, 1), 2, 10));
end func;</
{{out}}
Line 3,887 ⟶ 4,759:
=={{header|Sidef}}==
{{trans|Perl}}
<
loop {
var len = xs.len
len >=
xs
}
return xs
Line 3,899 ⟶ 4,771:
say fib(i).join(' ')
}
say fib(2, [2, 1]).join(' ')</
{{out}}
<pre>
Line 3,912 ⟶ 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}}
<
proc fibber {args} {
Line 3,945 ⟶ 4,907:
print10 [fibber 1 1 2 4]
puts "LUCAS"
print10 [fibber 2 1]</
{{out}}
<pre>
Line 3,959 ⟶ 4,921:
=={{header|VBA}}==
<
Sub Main()
Line 4,020 ⟶ 4,982:
Next
Fibonacci_Step = R
End Function</
{{Out}}
Line 4,027 ⟶ 4,989:
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">
'function arguments:
'init - initial series of the sequence(e.g. "1,1")
Line 4,062 ⟶ 5,023:
WScript.StdOut.Write "lucas: " & generate_seq("2,1",15)
WScript.StdOut.WriteLine
</syntaxhighlight>
{{Out}}
Line 4,070 ⟶ 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}}==
<
proc Nacci(N, F0); \Generate Fibonacci N-step sequence
Line 4,095 ⟶ 5,208:
Text(0, "Tetranacci: "); Nacci(4, [1, 1, 2, 4]);
Text(0, " Lucas: "); Nacci(2, [2, 1]);
]</
Output:
Line 4,107 ⟶ 5,220:
=={{header|Yabasic}}==
{{trans|Lua}}
<
local iMax, sum, numb$(1), lim, i
Line 4,127 ⟶ 5,240:
print "Tribonacci:", nStepFibs$("1,1,2", 10)
print "Tetranacci:", nStepFibs$("1,1,2,4", 10)
print "Lucas:", nStepFibs$("2,1", 10)</
=={{header|zkl}}==
<
This stores the initial n terms of the sequence and returns a function that, at each call, appends the sum of the terms to the sequence then pops the leading value and returns it.
<
lucas:=fibN(2,1); do(N){ lucas().print(","); } println(); // Lucas
ns:=L(1); foreach _ in ([ns.len()+1..10]){ // Fibonacci n-step for 2 .. 10
Line 4,138 ⟶ 5,251:
"%2d: ".fmt(ns.len()).print();
(N).pump(List,fibN(ns.xplode())).println();
}</
{{out}}
<pre>
|