Fibonacci n-step number sequences: Difference between revisions

Added various BASIC dialects (Chipmunk Basic, QBasic, and QB64)
m (→‎{{header|C sharp}}: Regularize header markup to recommended on category page)
(Added various BASIC dialects (Chipmunk Basic, QBasic, and QB64))
 
(16 intermediate revisions by 13 users not shown)
Line 63:
{{trans|Python: Callable class}}
 
<langsyntaxhighlight lang="11l">T Fiblike
Int addnum
[Int] memo
Line 87:
L(n, name) zip(2..10, ‘fibo tribo tetra penta hexa hepta octo nona deca’.split(‘ ’))
V fibber = Fiblike([1] [+] (0 .< n - 1).map(i -> Int(2 ^ i)))
print(‘n=#2, #5nacci -> #. ...’.format(n, name, (0.<15).map(i -> String(@fibber(i))).join(‘ ’)))</langsyntaxhighlight>
 
{{out}}
Line 105:
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Fibonacci n-step number sequences - 14/04/2020
FIBONS CSECT
USING FIBONS,R13 base register
Line 192:
PG DS CL120 buffer
REGEQU
END FIBONS</langsyntaxhighlight>
{{out}}
<pre>
Line 204:
 
=={{header|ACL2}}==
<langsyntaxhighlight lang="lisp">(defun sum (xs)
(if (endp xs)
0
Line 216:
(list (sum prevs)))))
(cons (first next)
(n-bonacci next (1- limit))))))</langsyntaxhighlight>
 
Output:
Line 229:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">DEFINE MAX="15"
 
PROC GenerateSeq(CARD ARRAY init BYTE nInit CARD ARRAY seq BYTE nSeq)
Line 303:
Test("nonanacci",fibInit,9,MAX)
Test("decanacci",fibInit,10,MAX)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Fibonacci_n-step_number_sequences.png Screenshot from Atari 8-bit computer]
Line 323:
First, we specify a package Bonacci, that defines the type Sequence (of Positive numbers), a function Generate that takes a given Start sequence and outputs a generalized N-Bonacci Sequence of a spefified Length, and some constant start sequences.
 
<langsyntaxhighlight Adalang="ada">package Bonacci is
 
type Sequence is array(Positive range <>) of Positive;
Line 333:
Start_Tetranacci: constant Sequence := (1, 1, 2, 4);
Start_Lucas: constant Sequence := (2, 1);
end Bonacci;</langsyntaxhighlight>
 
The implementation is quite straightforward.
 
<langsyntaxhighlight Adalang="ada">package body Bonacci is
 
function Generate(Start: Sequence; Length: Positive := 10) return Sequence is
Line 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 380:
Print("Decanacci: ",
Bonacci.Generate((1, 1, 2, 4, 8, 16, 32, 64, 128, 256), 15));
end Test_Bonacci;</langsyntaxhighlight>
 
The output:
Line 391:
 
=={{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 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 432:
=={{header|APL}}==
{{works with|Dyalog APL}}
<langsyntaxhighlight APLlang="apl">nStep ← {⊃(1↓⊢,+/)⍣(⍺-1)⊢⍵}
nacci ← 2*0⌈¯2+⍳
↑((⍳10)nStep¨⊂)¨(nacci¨2 3 4),⊂2 1</langsyntaxhighlight>
{{out}}
<pre>1 1 2 3 5 8 13 21 34 55
Line 443:
=={{header|AppleScript}}==
===Functional===
<langsyntaxhighlight lang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
Line 687:
end tell
end zipWith
</syntaxhighlight>
</lang>
{{Out}}
<pre>Lucas -> [2,1,3,4,7,11,18,29,47,76,123,199,322,521,843]
Line 702:
===Simple===
 
<langsyntaxhighlight lang="applescript">-- Parameters:
-- n: …nacci step size as integer. Alternatively "Lucas".
-- F: Maximum …nacci index required. (0-based.)
Line 745:
set AppleScript's text item delimiters to astid
 
return output</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight 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 …
Line 757:
nonanacci: 0, 1, 1, 2, 4, 8, 16, 32, 64, 128, 256, 511, 1021, 2040, 4076, 8144 …
decanacci: 0, 1, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1023, 2045, 4088, 8172 …
Lucas: 2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322, 521, 843, 1364 …"</langsyntaxhighlight>
 
=={{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 776 ⟶ 816:
}
return, a
}</langsyntaxhighlight>
'''Output:'''
<pre>nacci(2): 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610
Line 798 ⟶ 838:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
function sequence(values, howmany) {
init_length = length(values)
Line 829 ⟶ 869:
print("lucas :\t\t",sequence(a, 10))
}
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 837 ⟶ 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}}==
<langsyntaxhighlight lang="dos">
@echo off
 
Line 888 ⟶ 1,112:
endlocal
exit /b
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 906 ⟶ 1,130:
=={{header|BBC BASIC}}==
The BBC BASIC '''SUM''' function is useful here.
<langsyntaxhighlight lang="bbcbasic"> @% = 5 : REM Column width
PRINT "Fibonacci:"
Line 932 ⟶ 1,156:
NEXT
f%(i%-1) = s%
ENDPROC</langsyntaxhighlight>
'''Output:'''
<pre>
Line 947 ⟶ 1,171:
=={{header|Befunge}}==
 
<langsyntaxhighlight lang="befunge">110p>>55+109"iccanaceD"22099v
v9013"Tetranacci"9014"Lucas"<
>"iccanobirT"2109"iccanobiF"v
Line 954 ⟶ 1,178:
_$.1+:77+`^vg03:_0g+>\:1+#^
50p-\30v v\<>\30g1-\^$$_:1-
05g04\g< >`#^_:40p30g0>^!:g</langsyntaxhighlight>
 
{{out}}
Line 966 ⟶ 1,190:
=={{header|Bracmat}}==
{{trans|PicoLisp}}
<langsyntaxhighlight lang="bracmat">( ( nacci
= Init Cnt N made tail
. ( plus
Line 1,006 ⟶ 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 1,020 ⟶ 1,244:
 
=={{header|BQN}}==
<langsyntaxhighlight lang="bqn">NStep ← ⊑(1↓⊢∾+´)∘⊢⍟⊣
Nacci ← (2⋆0∾↕)∘(⊢-1˙)
 
>((↕10) NStep¨ <)¨ (Nacci¨ 2‿3‿4) ∾ <2‿1</langsyntaxhighlight>
{{out}}
<pre>┌─
Line 1,033 ⟶ 1,257:
 
=={{header|C}}==
<langsyntaxhighlight 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 1,075 ⟶ 1,299:
 
return 0;
}</langsyntaxhighlight>
 
Output:
Line 1,094 ⟶ 1,318:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 1,177 ⟶ 1,401:
}
}
}</langsyntaxhighlight>
<pre>Fibonacci 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,
Lucas 2, 1, 3, 4, 7, 11, 18, 29, 47, 76,
Line 1,184 ⟶ 1,408:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <vector>
#include <iostream>
#include <numeric>
Line 1,233 ⟶ 1,457:
}
return 0 ;
}</langsyntaxhighlight>
Output:
<pre>fibonacci : 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
Line 1,258 ⟶ 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 1,324 ⟶ 1,548:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn nacci [init]
(letfn [(s [] (lazy-cat init (apply map + (map #(drop % (s)) (range (count init))))))]
(s)))
Line 1,335 ⟶ 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 1,343 ⟶ 1,567:
 
=={{header|CLU}}==
<langsyntaxhighlight 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)
Line 1,389 ⟶ 1,613:
print_n(seq.seq, 10)
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>Fibonacci 1 1 2 3 5 8 13 21 34 55
Line 1,397 ⟶ 1,621:
 
=={{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 1,415 ⟶ 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 1,424 ⟶ 1,648:
=={{header|D}}==
===Basic Memoization===
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm, std.range, std.conv;
 
Line 1,452 ⟶ 1,676:
15.iota.map!fibber);
}
}</langsyntaxhighlight>
{{out}}
<pre>[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Line 1,468 ⟶ 1,692:
===Callable Struct===
The output is similar.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.conv;
 
struct fiblike(T) {
Line 1,502 ⟶ 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 1,549 ⟶ 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 1,570 ⟶ 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 1,585 ⟶ 1,809:
=={{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 1,610 ⟶ 1,863:
(make-nacci name seed)
(printf "%s[%d] → %d" name (vector-length seed) (take name 16))))
</syntaxhighlight>
</lang>
{{out}}
Line 1,626 ⟶ 1,879:
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule RC do
def anynacci(start_sequence, count) do
n = length(start_sequence)
Line 1,654 ⟶ 1,907:
:io.format("~11s: ", [name])
IO.inspect RC.anynacci(list, 15)
end)</langsyntaxhighlight>
 
{{out}}
Line 1,671 ⟶ 1,924:
 
=={{header|Erlang}}==
<syntaxhighlight lang="text">
-module( fibonacci_nstep ).
 
Line 1,693 ⟶ 1,946:
{Sum_ns, _Not_sum_ns} = lists:split( Nth, Ns ),
{Nth, [lists:sum(Sum_ns) | Ns]}.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,704 ⟶ 1,957:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM FIBON
 
Line 1,748 ⟶ 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,774 ⟶ 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,789 ⟶ 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.
<langsyntaxhighlight lang="factor">USING: formatting fry kernel make math namespaces qw sequences ;
 
: n-bonacci ( n initial -- seq ) [
Line 1,798 ⟶ 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</langsyntaxhighlight>
{{out}}
<pre>
Line 1,808 ⟶ 2,061:
 
=={{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,832 ⟶ 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,841 ⟶ 2,094:
 
=={{header|Fortran}}==
<langsyntaxhighlight lang="fortran">
! save this program as file f.f08
! gnu-linux command to build and test
Line 1,906 ⟶ 2,159:
end subroutine nacci
end program f
</syntaxhighlight>
</lang>
 
<pre>
Line 1,948 ⟶ 2,201:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' Deduces the step, n, from the length of the dynamic array passed in
Line 1,998 ⟶ 2,251:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 2,009 ⟶ 2,262:
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">import util.TextTable
native scala.collection.mutable.Queue
 
Line 2,039 ⟶ 2,292:
t.row( ([k] + [seqs(i)(k) | i <- 0:4]).toIndexedSeq() )
 
print( t )</langsyntaxhighlight>
 
{{out}}
Line 2,062 ⟶ 2,315:
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Fibonacci_n-step_number_sequences}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Solution'''
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
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 '''[https://formulae.org/?example=Fibonacci_n-step_number_sequences this]''' page you can see the program(s) related to this task and their results.
 
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.
<langsyntaxhighlight Golang="go">package main
 
import "fmt"
Line 2,108 ⟶ 2,415:
fmt.Println()
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,119 ⟶ 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 2,132 ⟶ 2,439:
}
}
}</langsyntaxhighlight>
=====Test=====
<langsyntaxhighlight lang="groovy">[
' fibonacci':[1,1],
'tribonacci':[1,1,2],
Line 2,150 ⟶ 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 2,166 ⟶ 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 2,200 ⟶ 2,511:
 
Or alternatively, without imports – using only the default Prelude:
<langsyntaxhighlight lang="haskell">------------ FIBONACCI N-STEP NUMBER SEQUENCES -----------
 
nStepFibonacci :: Int -> [Int]
Line 2,232 ⟶ 2,543:
 
justifyLeft :: Int -> Char -> String -> String
justifyLeft n c s = take n (s <> replicate n c)</langsyntaxhighlight>
<pre>Lucas -> [2,1,3,4,7,11,18,29,47,76,123,199,322,521,843]
fibonaccci -> [1,1,2,3,5,8,13,21,34,55,89,144,233,377,610]
Line 2,246 ⟶ 2,557:
or in terms of '''unfoldr''':
{{Trans|Python}}
<langsyntaxhighlight lang="haskell">import Data.Bifunctor (second)
import Data.List (transpose, uncons, unfoldr)
 
Line 2,303 ⟶ 2,614:
 
justifyRight :: Int -> Char -> String -> String
justifyRight n c = (drop . length) <*> (replicate n c <>)</langsyntaxhighlight>
{{Out}}
<pre>Recurrence relation sequences:
Line 2,321 ⟶ 2,632:
 
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 2,335 ⟶ 2,646:
suspend cache[i]
}
end</langsyntaxhighlight>
 
Output:
Line 2,350 ⟶ 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 2,359 ⟶ 2,670:
suspend cache[i]
}
end</langsyntaxhighlight>
 
The output is identical.
Line 2,365 ⟶ 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 2,390 ⟶ 2,701:
octonacci ✓
nonanacci ✓
decanacci ✓</langsyntaxhighlight>
 
=={{header|Java}}==
Line 2,396 ⟶ 2,707:
'''Code:'''
 
<langsyntaxhighlight lang="java">class Fibonacci
{
public static int[] lucas(int n, int numRequested)
Line 2,440 ⟶ 2,751:
}
}
}</langsyntaxhighlight>
 
Output:
Line 2,464 ⟶ 2,775:
=={{header|JavaScript}}==
===ES5===
<langsyntaxhighlight JavaScriptlang="javascript">function fib(arity, len) {
return nacci(nacci([1,1], arity, arity), arity, len);
}
Line 2,489 ⟶ 2,800:
}
 
main();</langsyntaxhighlight>
{{out}}
<pre>fib(2): 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610
Line 2,511 ⟶ 2,822:
 
===ES6===
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 2,624 ⟶ 2,935:
// MAIN ---
return main();
})();</langsyntaxhighlight>
<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,638 ⟶ 2,949:
=={{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 2,652 ⟶ 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 2,670 ⟶ 2,981:
 
'''Generalized Fibonacci Iterator Definition'''
<syntaxhighlight lang="julia">
<lang Julia>
type NFib{T<:Integer}
n::T
Line 2,701 ⟶ 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 2,716 ⟶ 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 2,732 ⟶ 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 2,747 ⟶ 3,058:
NFib(n, k, luc_seeder)
end
</syntaxhighlight>
</lang>
 
'''Main'''
<syntaxhighlight lang="julia">
<lang Julia>
lo = 2
hi = 10
Line 2,786 ⟶ 3,097:
println()
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,825 ⟶ 3,136:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun fibN(initial: IntArray, numTerms: Int) : IntArray {
Line 2,851 ⟶ 3,162:
println("%2d %-10s %s".format(i + 2, names[i], values))
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,869 ⟶ 3,180:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">function nStepFibs (seq, limit)
local iMax, sum = #seq - 1
while #seq < limit do
Line 2,888 ⟶ 3,199:
io.write(sequence.name .. ": ")
print(table.concat(nStepFibs(sequence.values, 10), " "))
end</langsyntaxhighlight>
{{out}}
<pre>Fibonacci: 1 1 2 3 5 8 13 21 34 55
Line 2,896 ⟶ 3,207:
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">numSequence := proc(initValues :: Array)
local n, i, values;
n := numelems(initValues);
Line 2,911 ⟶ 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 2,927 ⟶ 3,238:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">
<lang Mathematica>
f2=Function[{l,k},
Module[{n=Length@l,m},
Line 2,934 ⟶ 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 2,961 ⟶ 3,272:
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import sequtils, strutils
 
proc fiblike(start: seq[int]): auto =
Line 2,987 ⟶ 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(" "), " ..."</langsyntaxhighlight>
Output:
<pre>@[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Line 3,004 ⟶ 3,315:
We will use lazy lists, so can get any amount of n-nacci numbers.
 
<langsyntaxhighlight lang="scheme">
(define (n-fib-iterator ll)
(cons (car ll)
(lambda ()
(n-fib-iterator (append (cdr ll) (list (fold + 0 ll)))))))
</syntaxhighlight>
</lang>
 
Testing:
<langsyntaxhighlight lang="scheme">
(print "2, fibonacci : " (ltake (n-fib-iterator '(1 1)) 15))
(print "3, tribonacci: " (ltake (n-fib-iterator '(1 1 2)) 15))
Line 3,025 ⟶ 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>
</lang>
 
=={{header|PARI/GP}}==
Line 3,031 ⟶ 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 3,047 ⟶ 3,358:
=={{header|Pascal}}==
{{works with|Free_Pascal}}
<langsyntaxhighlight lang="pascal">program FibbonacciN (output);
 
type
Line 3,116 ⟶ 3,427:
write(sequence[k], ' ');
writeln;
end.</langsyntaxhighlight>
Output:
<pre>% ./Fibbonacci
Line 3,137 ⟶ 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 3,250 ⟶ 3,561:
write(NextNacci(Nacci),' ');
writeln;
END.</langsyntaxhighlight>
 
=={{header|PascalABC.NET}}==
===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
1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 13624 26784 52656 103519 203513
1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 15109 29970 59448 117920 233904
1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 15808 31489 62725 124946 248888
1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 16128 32192 64256 128257 256005
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}}==
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature <say signatures>;
Line 3,268 ⟶ 3,635:
 
say $_-1 . ': ' . join ' ', (fib_n $_)[0..19] for 2..10;
say "\nLucas: " . join ' ', fib_n(2, [2,1], 20);</langsyntaxhighlight>
{{out}}
<pre>1: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
Line 3,283 ⟶ 3,650:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="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>
Line 3,303 ⟶ 3,670:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,313 ⟶ 3,680:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
/**
* @author Elad Yosifon
Line 3,394 ⟶ 3,761:
}
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,410 ⟶ 3,777:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de nacci (Init Cnt)
(let N (length Init)
(make
(made Init)
(do (- Cnt N)
(link (apply + (tail N (made)))) ) ) ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp"># Fibonacci
: (nacci (1 1) 10)
-> (1 1 2 3 5 8 13 21 34 55)
Line 3,435 ⟶ 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)</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">(subscriptrange, fixedoverflow, size):
n_step_Fibonacci: procedure options (main);
declare line character (100) varying;
Line 3,465 ⟶ 3,832:
end;
end;
end n_step_Fibonacci;</langsyntaxhighlight>
Output:
<pre>
Line 3,485 ⟶ 3,852:
 
=={{header|Powershell}}==
<langsyntaxhighlight Powershelllang="powershell">#Create generator of extended fibonaci
Function Get-ExtendedFibonaciGenerator($InitialValues ){
$Values = $InitialValues
Line 3,502 ⟶ 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 3,516 ⟶ 3,883:
}
} | Format-Table -AutoSize
</syntaxhighlight>
</lang>
Sample output
<pre>
Line 3,533 ⟶ 3,900:
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">
<lang PureBasic>
 
Procedure.i FibonacciLike(k,n=2,p.s="",d.s=".")
Line 3,590 ⟶ 3,957:
Debug ""
 
</syntaxhighlight>
</lang>
 
'''Sample Output'''
Line 3,612 ⟶ 3,979:
=={{header|Python}}==
===Python: function returning a function===
<langsyntaxhighlight lang="python">>>> def fiblike(start):
addnum = len(start)
memo = start[:]
Line 3,644 ⟶ 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 3,680 ⟶ 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 3,701 ⟶ 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 3,718 ⟶ 4,085:
Defining the Lucas series and the N-Step Fibonacci series in terms of unfoldr (dual to functools.reduce).
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Fibonacci n-step number sequences'''
 
from itertools import chain, count, islice
Line 3,843 ⟶ 4,210:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Recurrence relation series:
Line 3,860 ⟶ 4,227:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ 0 swap witheach + ] is sum ( [ --> n )
 
[ tuck size -
Line 3,882 ⟶ 4,249:
' [ fibonacci tribonacci tetranacci lucas ]
witheach
[ dup echo say ": " 10 swap do echo cr ]</langsyntaxhighlight>
 
{{out}}
Line 3,893 ⟶ 4,260:
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
 
;; fib-list : [Listof Nat] x Nat -> [Listof Nat]
Line 3,917 ⟶ 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 3,935 ⟶ 4,302:
 
===Lazy List with Closure===
<syntaxhighlight lang="raku" perl6line>sub nacci ( $s = 2, :@start = (1,) ) {
my @seq = |@start, { state $n = +@start; @seq[ ($n - $s .. $n++ - 1).grep: * >= 0 ].sum } … *;
}
Line 3,941 ⟶ 4,308:
put "{.fmt: '%2d'}-nacci: ", nacci($_)[^20] for 2..12 ;
 
put "Lucas: ", nacci(:start(2,1))[^20];</langsyntaxhighlight>
{{out}}
<pre> 2-nacci: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
Line 3,959 ⟶ 4,326:
A slightly more straight forward way of constructing a lazy list.
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku" perl6line>sub fib ($n, @xs is copy = [1]) {
flat gather {
take @xs[*];
Line 3,973 ⟶ 4,340:
say fib($n, [1])[^20];
}
say fib(2, [2,1])[^20];</langsyntaxhighlight>
 
=={{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 4,010 ⟶ 4,377:
 
say right(Fname,11)'[sum'right(N,3) "terms]:" strip(L) '···'
return</langsyntaxhighlight>
'''output''' &nbsp; when using the default input:
<pre>
Line 4,029 ⟶ 4,396:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Fibonacci n-step number sequences
 
Line 4,091 ⟶ 4,458:
next
see svect
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,105 ⟶ 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}}==
<langsyntaxhighlight lang="ruby">def anynacci(start_sequence, count)
n = start_sequence.length # Get the n-step for the type of fibonacci sequence
result = start_sequence.dup # Create a new result array with the values copied from the array that was passed by reference
Line 4,128 ⟶ 4,516:
decanacci: [1,1,2,4,8,16,32,64,128,256] }
 
naccis.each {|name, seq| puts "%12s : %p" % [name, anynacci(seq, 15)]}</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="ruby"> 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]
Line 4,140 ⟶ 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 4,164 ⟶ 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 4,214 ⟶ 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.
Line 4,234 ⟶ 4,624:
inner(init.toVector)
}
</syntaxhighlight>
</lang>
 
===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
Line 4,249 ⟶ 4,639:
init.to(LazyList) #::: inner(init.toVector)
}
</syntaxhighlight>
</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
Line 4,264 ⟶ 4,654:
v.to(LazyList) #::: inner(v)
}
</syntaxhighlight>
</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 4,283 ⟶ 4,673:
=={{header|Scheme}}==
 
<langsyntaxhighlight lang="scheme">
(import (scheme base)
(scheme write)
Line 4,310 ⟶ 4,700:
(display (n-fib '(2 1) 15))
(newline)
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,321 ⟶ 4,711:
 
=={{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 4,357 ⟶ 4,747:
print("Tetranacci", bonacci([] (1, 1), 4, 10));
print("Lucas", bonacci([] (2, 1), 2, 10));
end func;</langsyntaxhighlight>
 
{{out}}
Line 4,369 ⟶ 4,759:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func fib(n, xs=[1], k=20) {
loop {
var len = xs.len
len >= k && break
xs << xs.ftslice(max(0, len - n)).sum
}
return xs
Line 4,381 ⟶ 4,771:
say fib(i).join(' ')
}
say fib(2, [2, 1]).join(' ')</langsyntaxhighlight>
{{out}}
<pre>
Line 4,397 ⟶ 4,787:
 
Using matrix exponentiation:
<langsyntaxhighlight lang="ruby">func fibonacci_matrix(k) is cached {
Matrix.build(k,k, {|i,j|
((i == k-1) || (i == j-1)) ? 1 : 0
Line 4,410 ⟶ 4,800:
for k in (2..9) {
say ("Fibonacci of k=#{k} order: ", (15+k).of { fibonacci_kth_order(_, k) })
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,424 ⟶ 4,814:
 
Faster algorithm:
<langsyntaxhighlight lang="ruby">func fibonacci_kth_order (n, k = 2) {
 
return 0 if (n < k-1)
Line 4,443 ⟶ 4,833:
for k in (2..9) {
say ("Fibonacci of k=#{k} order: ", (15+k).of { fibonacci_kth_order(_, k) })
}</langsyntaxhighlight>
(same output as above)
 
=={{header|Tailspin}}==
<langsyntaxhighlight lang="tailspin">
templates fibonacciNstep&{N:}
templates next
Line 4,477 ⟶ 4,867:
'
' -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,488 ⟶ 4,878:
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
proc fibber {args} {
Line 4,517 ⟶ 4,907:
print10 [fibber 1 1 2 4]
puts "LUCAS"
print10 [fibber 2 1]</langsyntaxhighlight>
{{out}}
<pre>
Line 4,531 ⟶ 4,921:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Option Explicit
 
Sub Main()
Line 4,592 ⟶ 4,982:
Next
Fibonacci_Step = R
End Function</langsyntaxhighlight>
 
{{Out}}
Line 4,601 ⟶ 4,991:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
'function arguments:
'init - initial series of the sequence(e.g. "1,1")
Line 4,633 ⟶ 5,023:
WScript.StdOut.Write "lucas: " & generate_seq("2,1",15)
WScript.StdOut.WriteLine
</syntaxhighlight>
</lang>
 
{{Out}}
Line 4,646 ⟶ 5,036:
{{trans|Visual Basic}}
{{works with|Visual Basic .NET|2011}}
<langsyntaxhighlight lang="vbnet">' Fibonacci n-step number sequences - VB.Net
Public Class FibonacciNstep
 
Line 4,683 ⟶ 5,073:
End Function 'FibonacciN
 
End Class 'FibonacciNstep</langsyntaxhighlight>
{{out}}
<pre>
Line 4,694 ⟶ 5,084:
</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}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
 
var fibN = Fn.new { |initial, numTerms|
Line 4,727 ⟶ 5,168:
Fmt.write("$2d $-10s", i + 2, names[i])
Fmt.aprint(values, 4, 0, "")
}</langsyntaxhighlight>
 
{{out}}
Line 4,745 ⟶ 5,186:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
 
proc Nacci(N, F0); \Generate Fibonacci N-step sequence
Line 4,767 ⟶ 5,208:
Text(0, "Tetranacci: "); Nacci(4, [1, 1, 2, 4]);
Text(0, " Lucas: "); Nacci(2, [2, 1]);
]</langsyntaxhighlight>
 
Output:
Line 4,779 ⟶ 5,220:
=={{header|Yabasic}}==
{{trans|Lua}}
<langsyntaxhighlight Yabasiclang="yabasic">sub nStepFibs$(seq$, limit)
local iMax, sum, numb$(1), lim, i
Line 4,799 ⟶ 5,240:
print "Tribonacci:", nStepFibs$("1,1,2", 10)
print "Tetranacci:", nStepFibs$("1,1,2,4", 10)
print "Lucas:", nStepFibs$("2,1", 10)</langsyntaxhighlight>
 
=={{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 4,810 ⟶ 5,251:
"%2d: ".fmt(ns.len()).print();
(N).pump(List,fibN(ns.xplode())).println();
}</langsyntaxhighlight>
{{out}}
<pre>
2,122

edits