Fibonacci n-step number sequences: Difference between revisions
Content deleted Content added
Not a robot (talk | contribs) Add CLU |
Added various BASIC dialects (Chipmunk Basic, QBasic, and QB64) |
||
(18 intermediate revisions by 14 users not shown) | |||
Line 63:
{{trans|Python: Callable class}}
<
Int addnum
[Int] memo
Line 87:
L(n, name) zip(2..10, ‘fibo tribo tetra penta hexa hepta octo nona deca’.split(‘ ’))
V fibber = Fiblike([1] [+] (0 .< n - 1).map(i -> Int(2 ^ i)))
print(‘n=#2, #5nacci -> #. ...’.format(n, name, (0.<15).map(i -> String(@fibber(i))).join(‘ ’)))</
{{out}}
Line 105:
=={{header|360 Assembly}}==
<
FIBONS CSECT
USING FIBONS,R13 base register
Line 192:
PG DS CL120 buffer
REGEQU
END FIBONS</
{{out}}
<pre>
Line 204:
=={{header|ACL2}}==
<
(if (endp xs)
0
Line 216:
(list (sum prevs)))))
(cons (first next)
(n-bonacci next (1- limit))))))</
Output:
Line 229:
=={{header|Action!}}==
<
PROC GenerateSeq(CARD ARRAY init BYTE nInit CARD ARRAY seq BYTE nSeq)
Line 303:
Test("nonanacci",fibInit,9,MAX)
Test("decanacci",fibInit,10,MAX)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Fibonacci_n-step_number_sequences.png Screenshot from Atari 8-bit computer]
Line 323:
First, we specify a package Bonacci, that defines the type Sequence (of Positive numbers), a function Generate that takes a given Start sequence and outputs a generalized N-Bonacci Sequence of a spefified Length, and some constant start sequences.
<
type Sequence is array(Positive range <>) of Positive;
Line 333:
Start_Tetranacci: constant Sequence := (1, 1, 2, 4);
Start_Lucas: constant Sequence := (2, 1);
end Bonacci;</
The implementation is quite straightforward.
<
function Generate(Start: Sequence; Length: Positive := 10) return Sequence is
Line 356:
end Generate;
end Bonacci;</
Finally, we actually generate some sequences, as required by the task. For convenience, we define a procedure Print that outputs a sequence,
<
procedure Test_Bonacci is
Line 380:
Print("Decanacci: ",
Bonacci.Generate((1, 1, 2, 4, 8, 16, 32, 64, 128, 256), 15));
end Test_Bonacci;</
The output:
Line 391:
=={{header|ALGOL 68}}==
<
# the initial values are taken from the init array #
PROC n step fibonacci sequence = ( []INT init, INT required count )[]INT:
Line 421:
print sequence( "tetrabonacci", n step fibonacci sequence( ( 1, 1, 2, 4 ), 10 ) );
print sequence( "lucus ", n step fibonacci sequence( ( 2, 1 ), 10 ) )
</syntaxhighlight>
{{out}}
<pre>
Line 432:
=={{header|APL}}==
{{works with|Dyalog APL}}
<
nacci ← 2*0⌈¯2+⍳
↑((⍳10)nStep¨⊂)¨(nacci¨2 3 4),⊂2 1</
{{out}}
<pre>1 1 2 3 5 8 13 21 34 55
Line 443:
=={{header|AppleScript}}==
===Functional===
<
use framework "Foundation"
use scripting additions
Line 687:
end tell
end zipWith
</syntaxhighlight>
{{Out}}
<pre>Lucas -> [2,1,3,4,7,11,18,29,47,76,123,199,322,521,843]
Line 702:
===Simple===
<
-- n: …nacci step size as integer. Alternatively "Lucas".
-- F: Maximum …nacci index required. (0-based.)
Line 745:
set AppleScript's text item delimiters to astid
return output</
{{output}}
<
tribonacci: 0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, 927, 1705, 3136 …
tetranacci: 0, 1, 1, 2, 4, 8, 15, 29, 56, 108, 208, 401, 773, 1490, 2872, 5536 …
Line 757:
nonanacci: 0, 1, 1, 2, 4, 8, 16, 32, 64, 128, 256, 511, 1021, 2040, 4076, 8144 …
decanacci: 0, 1, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1023, 2045, 4088, 8172 …
Lucas: 2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322, 521, 843, 1364 …"</
=={{header|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 776 ⟶ 816:
}
return, a
}</
'''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">
function sequence(values, howmany) {
init_length = length(values)
Line 829 ⟶ 869:
print("lucas :\t\t",sequence(a, 10))
}
</syntaxhighlight>
'''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}}==
<
@echo off
Line 888 ⟶ 1,112:
endlocal
exit /b
</syntaxhighlight>
{{out}}
<pre>
Line 906 ⟶ 1,130:
=={{header|BBC BASIC}}==
The BBC BASIC '''SUM''' function is useful here.
<
PRINT "Fibonacci:"
Line 932 ⟶ 1,156:
NEXT
f%(i%-1) = s%
ENDPROC</
'''Output:'''
<pre>
Line 947 ⟶ 1,171:
=={{header|Befunge}}==
<
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</
{{out}}
Line 966 ⟶ 1,190:
=={{header|Bracmat}}==
{{trans|PicoLisp}}
<
= Init Cnt N made tail
. ( plus
Line 1,006 ⟶ 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 1,020 ⟶ 1,244:
=={{header|BQN}}==
<
Nacci ← (2⋆0∾↕)∘(⊢-1˙)
>((↕10) NStep¨ <)¨ (Nacci¨ 2‿3‿4) ∾ <2‿1</
{{out}}
<pre>┌─
Line 1,033 ⟶ 1,257:
=={{header|C}}==
<
The function anynacci determines the n-arity of the sequence from the number of seed elements. 0 ended arrays are used since C does not have a way of determining the length of dynamic and function-passed integer arrays.*/
Line 1,075 ⟶ 1,299:
return 0;
}</
Output:
Line 1,093 ⟶ 1,317:
</pre>
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
using System.Linq;
Line 1,177 ⟶ 1,401:
}
}
}</
<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++}}==
<
#include <iostream>
#include <numeric>
Line 1,233 ⟶ 1,457:
}
return 0 ;
}</
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.
<
#include <iostream>
#include <vector>
Line 1,324 ⟶ 1,548:
}
}
</syntaxhighlight>
=={{header|Clojure}}==
<
(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]))</
{{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}}==
<
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</
{{out}}
<pre>Fibonacci 1 1 2 3 5 8 13 21 34 55
Line 1,397 ⟶ 1,621:
=={{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,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))))</
{{out}}
<pre>Lucas series: (2 1 3 4 7 11 18 29 47 76)
Line 1,424 ⟶ 1,648:
=={{header|D}}==
===Basic Memoization===
<
import std.stdio, std.algorithm, std.range, std.conv;
Line 1,452 ⟶ 1,676:
15.iota.map!fibber);
}
}</
{{out}}
<pre>[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Line 1,468 ⟶ 1,692:
===Callable Struct===
The output is similar.
<
struct fiblike(T) {
Line 1,502 ⟶ 1,726:
n, name, 15.iota.map!fib);
}
}</
===Struct With opApply===
The output is similar.
<
struct Fiblike(T) {
Line 1,549 ⟶ 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,570 ⟶ 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,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}}==
<
;; 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>
{{out}}
Line 1,626 ⟶ 1,879:
=={{header|Elixir}}==
{{trans|Ruby}}
<
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)</
{{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>
{{out}}
<pre>
Line 1,704 ⟶ 1,957:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM FIBON
Line 1,748 ⟶ 2,001:
FIB("Lucas","2,1")
END PROGRAM
</syntaxhighlight>
=={{header|F_Sharp|F#}}==
<
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</
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.
<
: 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</
{{out}}
<pre>
Line 1,808 ⟶ 2,061:
=={{header|Forth}}==
<
: 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>
{{out}}
<pre>fibonacci: 1 1 2 3 5 8 13 21 34 55
Line 1,841 ⟶ 2,094:
=={{header|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>
<pre>
Line 1,948 ⟶ 2,201:
=={{header|FreeBASIC}}==
<
' 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</
{{out}}
Line 2,009 ⟶ 2,262:
=={{header|FunL}}==
<
native scala.collection.mutable.Queue
Line 2,039 ⟶ 2,292:
t.row( ([k] + [seqs(i)(k) | i <- 0:4]).toIndexedSeq() )
print( t )</
{{out}}
Line 2,062 ⟶ 2,315:
=={{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 2,108 ⟶ 2,415:
fmt.Println()
}
}</
{{out}}
<pre>
Line 2,119 ⟶ 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 2,132 ⟶ 2,439:
}
}
}</
=====Test=====
<
' 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)}"</
{{out}}
<pre> fibonacci: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Line 2,166 ⟶ 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 2,200 ⟶ 2,511:
Or alternatively, without imports – using only the default Prelude:
<
nStepFibonacci :: Int -> [Int]
Line 2,232 ⟶ 2,543:
justifyLeft :: Int -> Char -> String -> String
justifyLeft n c s = take n (s <> replicate n c)</
<pre>Lucas -> [2,1,3,4,7,11,18,29,47,76,123,199,322,521,843]
fibonaccci -> [1,1,2,3,5,8,13,21,34,55,89,144,233,377,610]
Line 2,246 ⟶ 2,557:
or in terms of '''unfoldr''':
{{Trans|Python}}
<
import Data.List (transpose, uncons, unfoldr)
Line 2,303 ⟶ 2,614:
justifyRight :: Int -> Char -> String -> String
justifyRight n c = (drop . length) <*> (replicate n c <>)</
{{Out}}
<pre>Recurrence relation sequences:
Line 2,321 ⟶ 2,632:
Works in both languages:
<
every writes("F2:\t"|right((fnsGen(1,1))\14,5) | "\n")
every writes("F3:\t"|right((fnsGen(1,1,2))\14,5) | "\n")
Line 2,335 ⟶ 2,646:
suspend cache[i]
}
end</
Output:
Line 2,350 ⟶ 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 2,359 ⟶ 2,670:
suspend cache[i]
}
end</
The output is identical.
Line 2,365 ⟶ 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 2,390 ⟶ 2,701:
octonacci ✓
nonanacci ✓
decanacci ✓</
=={{header|Java}}==
Line 2,396 ⟶ 2,707:
'''Code:'''
<
{
public static int[] lucas(int n, int numRequested)
Line 2,440 ⟶ 2,751:
}
}
}</
Output:
Line 2,464 ⟶ 2,775:
=={{header|JavaScript}}==
===ES5===
<
return nacci(nacci([1,1], arity, arity), arity, len);
}
Line 2,489 ⟶ 2,800:
}
main();</
{{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===
<
'use strict';
Line 2,624 ⟶ 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,638 ⟶ 2,949:
=={{header|jq}}==
{{Works with|jq|1.4}}
<
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) ;</
'''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,670 ⟶ 2,981:
'''Generalized Fibonacci Iterator Definition'''
<syntaxhighlight lang="julia">
type NFib{T<:Integer}
n::T
Line 2,701 ⟶ 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,716 ⟶ 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,732 ⟶ 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,747 ⟶ 3,058:
NFib(n, k, luc_seeder)
end
</syntaxhighlight>
'''Main'''
<syntaxhighlight lang="julia">
lo = 2
hi = 10
Line 2,786 ⟶ 3,097:
println()
end
</syntaxhighlight>
{{out}}
Line 2,825 ⟶ 3,136:
=={{header|Kotlin}}==
<
fun fibN(initial: IntArray, numTerms: Int) : IntArray {
Line 2,851 ⟶ 3,162:
println("%2d %-10s %s".format(i + 2, names[i], values))
}
}</
{{out}}
Line 2,869 ⟶ 3,180:
=={{header|Lua}}==
<
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</
{{out}}
<pre>Fibonacci: 1 1 2 3 5 8 13 21 34 55
Line 2,896 ⟶ 3,207:
=={{header|Maple}}==
<
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));</
{{out}}
<pre>
Line 2,927 ⟶ 3,238:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight 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>
Output:
<pre>
Line 2,961 ⟶ 3,272:
=={{header|Nim}}==
{{trans|Python}}
<
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(" "), " ..."</
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.
<
(define (n-fib-iterator ll)
(cons (car ll)
(lambda ()
(n-fib-iterator (append (cdr ll) (list (fold + 0 ll)))))))
</syntaxhighlight>
Testing:
<
(print "2, fibonacci : " (ltake (n-fib-iterator '(1 1)) 15))
(print "3, tribonacci: " (ltake (n-fib-iterator '(1 1 2)) 15))
Line 3,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>
=={{header|PARI/GP}}==
Line 3,031 ⟶ 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 3,047 ⟶ 3,358:
=={{header|Pascal}}==
{{works with|Free_Pascal}}
<
type
Line 3,116 ⟶ 3,427:
write(sequence[k], ' ');
writeln;
end.</
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}}
<
program FibbonacciN (output);
{$IFNDEF FPC}
Line 3,250 ⟶ 3,561:
write(NextNacci(Nacci),' ');
writeln;
END.</
=={{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}}==
<
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);</
{{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}}==
<!--<
<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>
Line 3,300 ⟶ 3,668:
<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: %
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<pre>
Line 3,312 ⟶ 3,680:
=={{header|PHP}}==
<
/**
* @author Elad Yosifon
Line 3,393 ⟶ 3,761:
}
</syntaxhighlight>
{{out}}
<pre>
Line 3,409 ⟶ 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,434 ⟶ 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,464 ⟶ 3,832:
end;
end;
end n_step_Fibonacci;</
Output:
<pre>
Line 3,484 ⟶ 3,852:
=={{header|Powershell}}==
<
Function Get-ExtendedFibonaciGenerator($InitialValues ){
$Values = $InitialValues
Line 3,501 ⟶ 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,515 ⟶ 3,883:
}
} | Format-Table -AutoSize
</syntaxhighlight>
Sample output
<pre>
Line 3,532 ⟶ 3,900:
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">
Procedure.i FibonacciLike(k,n=2,p.s="",d.s=".")
Line 3,589 ⟶ 3,957:
Debug ""
</syntaxhighlight>
'''Sample Output'''
Line 3,611 ⟶ 3,979:
=={{header|Python}}==
===Python: function returning a function===
<
addnum = len(start)
memo = start[:]
Line 3,643 ⟶ 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,679 ⟶ 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,700 ⟶ 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,717 ⟶ 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}}
<
from itertools import chain, count, islice
Line 3,842 ⟶ 4,210:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>Recurrence relation series:
Line 3,859 ⟶ 4,227:
=={{header|Quackery}}==
<
[ tuck size -
Line 3,881 ⟶ 4,249:
' [ fibonacci tribonacci tetranacci lucas ]
witheach
[ dup echo say ": " 10 swap do echo cr ]</
{{out}}
Line 3,892 ⟶ 4,260:
=={{header|Racket}}==
<
;; fib-list : [Listof Nat] x Nat -> [Listof Nat]
Line 3,916 ⟶ 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,934 ⟶ 4,302:
===Lazy List with Closure===
<syntaxhighlight lang="raku"
my @seq = |@start, { state $n = +@start; @seq[ ($n - $s .. $n++ - 1).grep: * >= 0 ].sum } … *;
}
Line 3,940 ⟶ 4,308:
put "{.fmt: '%2d'}-nacci: ", nacci($_)[^20] for 2..12 ;
put "Lucas: ", nacci(:start(2,1))[^20];</
{{out}}
<pre> 2-nacci: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
Line 3,958 ⟶ 4,326:
A slightly more straight forward way of constructing a lazy list.
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku"
flat gather {
take @xs[*];
Line 3,972 ⟶ 4,340:
say fib($n, [1])[^20];
}
say fib(2, [2,1])[^20];</
=={{header|REXX}}==
<
parse arg FibName values /*allows a Fibonacci name, starter vals*/
if FibName\='' then do; call nStepFib FibName,values; signal done; end
Line 4,009 ⟶ 4,377:
say right(Fname,11)'[sum'right(N,3) "terms]:" strip(L) '···'
return</
'''output''' when using the default input:
<pre>
Line 4,028 ⟶ 4,396:
=={{header|Ring}}==
<
# Project : Fibonacci n-step number sequences
Line 4,090 ⟶ 4,458:
next
see svect
</syntaxhighlight>
Output:
<pre>
Line 4,104 ⟶ 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}}==
<
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,127 ⟶ 4,516:
decanacci: [1,1,2,4,8,16,32,64,128,256] }
naccis.each {|name, seq| puts "%12s : %p" % [name, anynacci(seq, 15)]}</
{{out}}
<
fibonacci : [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
tribonacci : [1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, 927, 1705, 3136]
Line 4,139 ⟶ 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 4,163 ⟶ 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 4,213 ⟶ 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.
Line 4,233 ⟶ 4,624:
inner(init.toVector)
}
</syntaxhighlight>
===Optimizing===
<
//in the optimized version we don't compute values until it's needed.
//the unoptimized version, computed k elements ahead, where k being
Line 4,248 ⟶ 4,639:
init.to(LazyList) #::: inner(init.toVector)
}
</syntaxhighlight>
===Optimizing Further===
<
//instead of summing k elements each phase, we exploit the fact
//that the last element is already the sum of all k preceding elements
Line 4,263 ⟶ 4,654:
v.to(LazyList) #::: inner(v)
}
</syntaxhighlight>
===Printing===
<
println(s"Fibonacci: ${fibStream(1,1).take(10).mkString(",")}")
println(s"Tribonacci: ${fibStream(1,1,2).take(10).mkString(",")}")
println(s"Tetranacci: ${fibStream(1,1,2,4).take(10).mkString(",")}")
println(s"Lucas: ${fibStream(2,1).take(10).mkString(",")}")
</syntaxhighlight>
{{out}}
<pre>
Line 4,282 ⟶ 4,673:
=={{header|Scheme}}==
<
(import (scheme base)
(scheme write)
Line 4,309 ⟶ 4,700:
(display (n-fib '(2 1) 15))
(newline)
</syntaxhighlight>
{{out}}
Line 4,320 ⟶ 4,711:
=={{header|Seed7}}==
<
const func array integer: bonacci (in array integer: start, in integer: arity, in integer: length) is func
Line 4,356 ⟶ 4,747:
print("Tetranacci", bonacci([] (1, 1), 4, 10));
print("Lucas", bonacci([] (2, 1), 2, 10));
end func;</
{{out}}
Line 4,368 ⟶ 4,759:
=={{header|Sidef}}==
{{trans|Perl}}
<
loop {
var len = xs.len
len >= k && break
xs << xs.
}
return xs
Line 4,380 ⟶ 4,771:
say fib(i).join(' ')
}
say fib(2, [2, 1]).join(' ')</
{{out}}
<pre>
Line 4,396 ⟶ 4,787:
Using matrix exponentiation:
<
Matrix.build(k,k, {|i,j|
((i == k-1) || (i == j-1)) ? 1 : 0
Line 4,409 ⟶ 4,800:
for k in (2..9) {
say ("Fibonacci of k=#{k} order: ", (15+k).of { fibonacci_kth_order(_, k) })
}</
{{out}}
<pre>
Line 4,423 ⟶ 4,814:
Faster algorithm:
<
return 0 if (n < k-1)
Line 4,442 ⟶ 4,833:
for k in (2..9) {
say ("Fibonacci of k=#{k} order: ", (15+k).of { fibonacci_kth_order(_, k) })
}</
(same output as above)
=={{header|Tailspin}}==
<
templates fibonacciNstep&{N:}
templates next
Line 4,476 ⟶ 4,867:
'
' -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
Line 4,487 ⟶ 4,878:
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<
proc fibber {args} {
Line 4,516 ⟶ 4,907:
print10 [fibber 1 1 2 4]
puts "LUCAS"
print10 [fibber 2 1]</
{{out}}
<pre>
Line 4,530 ⟶ 4,921:
=={{header|VBA}}==
<
Sub Main()
Line 4,591 ⟶ 4,982:
Next
Fibonacci_Step = R
End Function</
{{Out}}
Line 4,600 ⟶ 4,991:
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
'function arguments:
'init - initial series of the sequence(e.g. "1,1")
Line 4,632 ⟶ 5,023:
WScript.StdOut.Write "lucas: " & generate_seq("2,1",15)
WScript.StdOut.WriteLine
</syntaxhighlight>
{{Out}}
Line 4,645 ⟶ 5,036:
{{trans|Visual Basic}}
{{works with|Visual Basic .NET|2011}}
<
Public Class FibonacciNstep
Line 4,682 ⟶ 5,073:
End Function 'FibonacciN
End Class 'FibonacciNstep</
{{out}}
<pre>
Line 4,693 ⟶ 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}}
<
var fibN = Fn.new { |initial, numTerms|
Line 4,726 ⟶ 5,168:
Fmt.write("$2d $-10s", i + 2, names[i])
Fmt.aprint(values, 4, 0, "")
}</
{{out}}
Line 4,744 ⟶ 5,186:
=={{header|XPL0}}==
<
proc Nacci(N, F0); \Generate Fibonacci N-step sequence
Line 4,766 ⟶ 5,208:
Text(0, "Tetranacci: "); Nacci(4, [1, 1, 2, 4]);
Text(0, " Lucas: "); Nacci(2, [2, 1]);
]</
Output:
Line 4,778 ⟶ 5,220:
=={{header|Yabasic}}==
{{trans|Lua}}
<
local iMax, sum, numb$(1), lim, i
Line 4,798 ⟶ 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,809 ⟶ 5,251:
"%2d: ".fmt(ns.len()).print();
(N).pump(List,fibN(ns.xplode())).println();
}</
{{out}}
<pre>
|