Jump to content

Fibonacci n-step number sequences: Difference between revisions

m
syntax highlighting fixup automation
No edit summary
m (syntax highlighting fixup automation)
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|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">for i, seq in ["nacci", "lucas"]
Loop, 9 {
Out .= seq "(" A_Index + 1 "): "
Line 776:
}
return, a
}</langsyntaxhighlight>
'''Output:'''
<pre>nacci(2): 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610
Line 798:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
function sequence(values, howmany) {
init_length = length(values)
Line 829:
print("lucas :\t\t",sequence(a, 10))
}
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 839:
 
=={{header|BASIC256}}==
<langsyntaxhighlight BASIC256lang="basic256"># Rosetta Code problem: https://www.rosettacode.org/wiki/Fibonacci_n-step_number_sequences
# by Jjuanhdez, 06/2022
 
Line 889:
next j
next i
end subroutine</langsyntaxhighlight>
{{out}}
<pre> fibonacci => 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, ...
Line 903:
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">
@echo off
 
Line 952:
endlocal
exit /b
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 970:
=={{header|BBC BASIC}}==
The BBC BASIC '''SUM''' function is useful here.
<langsyntaxhighlight lang="bbcbasic"> @% = 5 : REM Column width
PRINT "Fibonacci:"
Line 996:
NEXT
f%(i%-1) = s%
ENDPROC</langsyntaxhighlight>
'''Output:'''
<pre>
Line 1,011:
=={{header|Befunge}}==
 
<langsyntaxhighlight lang="befunge">110p>>55+109"iccanaceD"22099v
v9013"Tetranacci"9014"Lucas"<
>"iccanobirT"2109"iccanobiF"v
Line 1,018:
_$.1+:77+`^vg03:_0g+>\:1+#^
50p-\30v v\<>\30g1-\^$$_:1-
05g04\g< >`#^_:40p30g0>^!:g</langsyntaxhighlight>
 
{{out}}
Line 1,030:
=={{header|Bracmat}}==
{{trans|PicoLisp}}
<langsyntaxhighlight lang="bracmat">( ( nacci
= Init Cnt N made tail
. ( plus
Line 1,070:
& 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,084:
 
=={{header|BQN}}==
<langsyntaxhighlight lang="bqn">NStep ← ⊑(1↓⊢∾+´)∘⊢⍟⊣
Nacci ← (2⋆0∾↕)∘(⊢-1˙)
 
>((↕10) NStep¨ <)¨ (Nacci¨ 2‿3‿4) ∾ <2‿1</langsyntaxhighlight>
{{out}}
<pre>┌─
Line 1,097:
 
=={{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,139:
 
return 0;
}</langsyntaxhighlight>
 
Output:
Line 1,158:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 1,241:
}
}
}</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,248:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <vector>
#include <iostream>
#include <numeric>
Line 1,297:
}
return 0 ;
}</langsyntaxhighlight>
Output:
<pre>fibonacci : 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
Line 1,322:
This version focuses on a clean, simple class that adapts to any pair of starting numbers and any order. Rather than summing over all history every time, it uses an O(1) incremental update to a running total. Thus, performance remains essentially unchanged even for very large orders.
 
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <vector>
Line 1,388:
}
}
</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,399:
(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,407:
 
=={{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,453:
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,461:
 
=={{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,479:
(format t "Lucas series: ~a~%" (gen-fib '(2 1) 10))
(loop for i from 2 to 4
do (format t "Fibonacci ~a-step sequence: ~a~%" i (gen-fib (initial-values i) 10))))</langsyntaxhighlight>
{{out}}
<pre>Lucas series: (2 1 3 4 7 11 18 29 47 76)
Line 1,488:
=={{header|D}}==
===Basic Memoization===
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm, std.range, std.conv;
 
Line 1,516:
15.iota.map!fibber);
}
}</langsyntaxhighlight>
{{out}}
<pre>[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Line 1,532:
===Callable Struct===
The output is similar.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.conv;
 
struct fiblike(T) {
Line 1,566:
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,613:
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,634:
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,650:
See [[#Pascal]].
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
;; generate a recursive lambda() for a x-nacci
;; equip it with memoïzation
Line 1,674:
(make-nacci name seed)
(printf "%s[%d] → %d" name (vector-length seed) (take name 16))))
</syntaxhighlight>
</lang>
{{out}}
Line 1,690:
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule RC do
def anynacci(start_sequence, count) do
n = length(start_sequence)
Line 1,718:
:io.format("~11s: ", [name])
IO.inspect RC.anynacci(list, 15)
end)</langsyntaxhighlight>
 
{{out}}
Line 1,735:
 
=={{header|Erlang}}==
<syntaxhighlight lang="text">
-module( fibonacci_nstep ).
 
Line 1,757:
{Sum_ns, _Not_sum_ns} = lists:split( Nth, Ns ),
{Nth, [lists:sum(Sum_ns) | Ns]}.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,768:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM FIBON
 
Line 1,812:
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,838:
(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,853:
=={{header|Factor}}==
<code>building</code> is a dynamic variable that refers to the sequence being built by <code>make</code>. This is useful when the next element of the sequence depends on previous elements.
<langsyntaxhighlight lang="factor">USING: formatting fry kernel make math namespaces qw sequences ;
 
: n-bonacci ( n initial -- seq ) [
Line 1,862:
qw{ fibonacci tribonacci tetranacci lucas }
{ { 1 1 } { 1 1 2 } { 1 1 2 4 } { 2 1 } }
[ 10 swap n-bonacci "%-10s %[%3d, %]\n" printf ] 2each</langsyntaxhighlight>
{{out}}
<pre>
Line 1,872:
 
=={{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,896:
." 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,905:
 
=={{header|Fortran}}==
<langsyntaxhighlight lang="fortran">
! save this program as file f.f08
! gnu-linux command to build and test
Line 1,970:
end subroutine nacci
end program f
</syntaxhighlight>
</lang>
 
<pre>
Line 2,012:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' Deduces the step, n, from the length of the dynamic array passed in
Line 2,062:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 2,073:
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">import util.TextTable
native scala.collection.mutable.Queue
 
Line 2,103:
t.row( ([k] + [seqs(i)(k) | i <- 0:4]).toIndexedSeq() )
 
print( t )</langsyntaxhighlight>
 
{{out}}
Line 2,134:
=={{header|Go}}==
Solution using separate goroutines.
<langsyntaxhighlight Golang="go">package main
 
import "fmt"
Line 2,172:
fmt.Println()
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,183:
=={{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,196:
}
}
}</langsyntaxhighlight>
=====Test=====
<langsyntaxhighlight lang="groovy">[
' fibonacci':[1,1],
'tribonacci':[1,1,2],
Line 2,214:
 
println " lucas[0]: ${fib([2,1],0)}"
println " tetra[3]: ${fib([1,1,2,4],3)}"</langsyntaxhighlight>
{{out}}
<pre> fibonacci: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Line 2,230:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List (tails)
import Control.Monad (zipWithM_)
 
Line 2,247:
zipWithM_ (\n name -> do putStr (name ++ "nacci -> ")
print $ take 15 $ nstep n)
[2..] (words "fibo tribo tetra penta hexa hepta octo nona deca")</langsyntaxhighlight>
{{out}}
<pre>
Line 2,264:
 
Or alternatively, without imports – using only the default Prelude:
<langsyntaxhighlight lang="haskell">------------ FIBONACCI N-STEP NUMBER SEQUENCES -----------
 
nStepFibonacci :: Int -> [Int]
Line 2,296:
 
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,310:
or in terms of '''unfoldr''':
{{Trans|Python}}
<langsyntaxhighlight lang="haskell">import Data.Bifunctor (second)
import Data.List (transpose, uncons, unfoldr)
 
Line 2,367:
 
justifyRight :: Int -> Char -> String -> String
justifyRight n c = (drop . length) <*> (replicate n c <>)</langsyntaxhighlight>
{{Out}}
<pre>Recurrence relation sequences:
Line 2,385:
 
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,399:
suspend cache[i]
}
end</langsyntaxhighlight>
 
Output:
Line 2,414:
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,423:
suspend cache[i]
}
end</langsyntaxhighlight>
 
The output is identical.
Line 2,429:
=={{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,454:
octonacci ✓
nonanacci ✓
decanacci ✓</langsyntaxhighlight>
 
=={{header|Java}}==
Line 2,460:
'''Code:'''
 
<langsyntaxhighlight lang="java">class Fibonacci
{
public static int[] lucas(int n, int numRequested)
Line 2,504:
}
}
}</langsyntaxhighlight>
 
Output:
Line 2,528:
=={{header|JavaScript}}==
===ES5===
<langsyntaxhighlight JavaScriptlang="javascript">function fib(arity, len) {
return nacci(nacci([1,1], arity, arity), arity, len);
}
Line 2,553:
}
 
main();</langsyntaxhighlight>
{{out}}
<pre>fib(2): 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610
Line 2,575:
 
===ES6===
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 2,688:
// 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,702:
=={{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,716:
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,734:
 
'''Generalized Fibonacci Iterator Definition'''
<syntaxhighlight lang="julia">
<lang Julia>
type NFib{T<:Integer}
n::T
Line 2,765:
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,780:
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,796:
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,811:
NFib(n, k, luc_seeder)
end
</syntaxhighlight>
</lang>
 
'''Main'''
<syntaxhighlight lang="julia">
<lang Julia>
lo = 2
hi = 10
Line 2,850:
println()
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,889:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun fibN(initial: IntArray, numTerms: Int) : IntArray {
Line 2,915:
println("%2d %-10s %s".format(i + 2, names[i], values))
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,933:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">function nStepFibs (seq, limit)
local iMax, sum = #seq - 1
while #seq < limit do
Line 2,952:
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,960:
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">numSequence := proc(initValues :: Array)
local n, i, values;
n := numelems(initValues);
Line 2,975:
printf ("nacci(%d): %a\n", i, convert(numSequence(initValues), list));
end do:
printf ("lucas: %a\n", convert(numSequence(Array([2, 1])), list));</langsyntaxhighlight>
{{out}}
<pre>
Line 2,991:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">
<lang Mathematica>
f2=Function[{l,k},
Module[{n=Length@l,m},
Line 2,998:
Table[Last/@f2[{1,1}~Join~Table[0,{n-2}],15+n][[-18;;]],{n,2,10}]//TableForm
Table[Last/@f2[{1,2}~Join~Table[0,{n-2}],15+n][[-18;;]],{n,2,10}]//TableForm
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,025:
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import sequtils, strutils
 
proc fiblike(start: seq[int]): auto =
Line 3,051:
se.add(1 shl i)
let fibber = fiblike(se)
echo "n = ", align($n, 2), ", ", align(name, 5), "nacci -> ", toSeq(0..14).mapIt($fibber(it)).join(" "), " ..."</langsyntaxhighlight>
Output:
<pre>@[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Line 3,068:
We will use lazy lists, so can get any amount of n-nacci numbers.
 
<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,089:
5, pentanacci: (1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930)
2, lucas : (2 1 3 4 7 11 18 29 47 76 123 199 322 521 843)
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
Line 3,095:
 
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,111:
=={{header|Pascal}}==
{{works with|Free_Pascal}}
<langsyntaxhighlight lang="pascal">program FibbonacciN (output);
 
type
Line 3,180:
write(sequence[k], ' ');
writeln;
end.</langsyntaxhighlight>
Output:
<pre>% ./Fibbonacci
Line 3,201:
Fib(n)/Fib(n-1) tends to the golden ratio = 1.618... 1.618^100 > 2^64
{{works with|Free_Pascal}}
<langsyntaxhighlight lang="pascal">
program FibbonacciN (output);
{$IFNDEF FPC}
Line 3,314:
write(NextNacci(Nacci),' ');
writeln;
END.</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature <say signatures>;
Line 3,332:
 
say $_-1 . ': ' . join ' ', (fib_n $_)[0..19] for 2..10;
say "\nLucas: " . join ' ', fib_n(2, [2,1], 20);</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,347:
 
=={{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,367:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%snacci: %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">names</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">f</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,377:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
/**
* @author Elad Yosifon
Line 3,458:
}
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,474:
 
=={{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,499:
# Decanacci
: (nacci (1 1 2 4 8 16 32 64 128 256) 15)
-> (1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172)</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">(subscriptrange, fixedoverflow, size):
n_step_Fibonacci: procedure options (main);
declare line character (100) varying;
Line 3,529:
end;
end;
end n_step_Fibonacci;</langsyntaxhighlight>
Output:
<pre>
Line 3,549:
 
=={{header|Powershell}}==
<langsyntaxhighlight Powershelllang="powershell">#Create generator of extended fibonaci
Function Get-ExtendedFibonaciGenerator($InitialValues ){
$Values = $InitialValues
Line 3,566:
}.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,580:
}
} | Format-Table -AutoSize
</syntaxhighlight>
</lang>
Sample output
<pre>
Line 3,597:
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">
<lang PureBasic>
 
Procedure.i FibonacciLike(k,n=2,p.s="",d.s=".")
Line 3,654:
Debug ""
 
</syntaxhighlight>
</lang>
 
'''Sample Output'''
Line 3,676:
=={{header|Python}}==
===Python: function returning a function===
<langsyntaxhighlight lang="python">>>> def fiblike(start):
addnum = len(start)
memo = start[:]
Line 3,708:
n= 9, nonanacci -> 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
n=10, decanacci -> 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
>>> </langsyntaxhighlight>
 
===Python: Callable class===
<langsyntaxhighlight lang="python">>>> class Fiblike():
def __init__(self, start):
self.addnum = len(start)
Line 3,744:
n= 9, nonanacci -> 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
n=10, decanacci -> 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
>>> </langsyntaxhighlight>
 
===Python: Generator===
<langsyntaxhighlight lang="python">from itertools import islice, cycle
 
def fiblike(tail):
Line 3,765:
fib = fiblike([1] + [2 ** i for i in xrange(n - 1)])
items = list(islice(fib, 15))
print "n=%2i, %5snacci -> %s ..." % (n, name, items)</langsyntaxhighlight>
{{out}}
<pre>[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Line 3,782:
Defining the Lucas series and the N-Step Fibonacci series in terms of unfoldr (dual to functools.reduce).
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Fibonacci n-step number sequences'''
 
from itertools import chain, count, islice
Line 3,907:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Recurrence relation series:
Line 3,924:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ 0 swap witheach + ] is sum ( [ --> n )
 
[ tuck size -
Line 3,946:
' [ fibonacci tribonacci tetranacci lucas ]
witheach
[ dup echo say ": " 10 swap do echo cr ]</langsyntaxhighlight>
 
{{out}}
Line 3,957:
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
 
;; fib-list : [Listof Nat] x Nat -> [Listof Nat]
Line 3,981:
(cons 1 (build-list (sub1 n) (curry expt 2)))))
;; and with an initial (2 1)
(show-fibs "lucas" '(2 1))</langsyntaxhighlight>
 
{{out}}
Line 3,999:
 
===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 4,005:
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 4,023:
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 4,037:
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,074:
 
say right(Fname,11)'[sum'right(N,3) "terms]:" strip(L) '···'
return</langsyntaxhighlight>
'''output''' &nbsp; when using the default input:
<pre>
Line 4,093:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Fibonacci n-step number sequences
 
Line 4,155:
next
see svect
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,172:
 
=={{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,192:
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,204:
nonanacci : [1, 1, 2, 4, 8, 16, 32, 64, 128, 256, 511, 1021, 2040, 4076, 8144]
decanacci : [1, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1023, 2045, 4088, 8172]
</syntaxhighlight>
</lang>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">a = fib(" fibonacci ", "1,1")
a = fib("tribonacci ", "1,1,2")
a = fib("tetranacci ", "1,1,2,4")
Line 4,228:
next i
print
end function</langsyntaxhighlight>
{{out}}
<pre> fibonacci => 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377,
Line 4,238:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
struct GenFibonacci {
buf: Vec<u64>,
Line 4,280:
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,300:
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,315:
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,330:
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,349:
=={{header|Scheme}}==
 
<langsyntaxhighlight lang="scheme">
(import (scheme base)
(scheme write)
Line 4,376:
(display (n-fib '(2 1) 15))
(newline)
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,387:
 
=={{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,423:
print("Tetranacci", bonacci([] (1, 1), 4, 10));
print("Lucas", bonacci([] (2, 1), 2, 10));
end func;</langsyntaxhighlight>
 
{{out}}
Line 4,435:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func fib(n, xs=[1], k=20) {
loop {
var len = xs.len
Line 4,447:
say fib(i).join(' ')
}
say fib(2, [2, 1]).join(' ')</langsyntaxhighlight>
{{out}}
<pre>
Line 4,463:
 
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,476:
for k in (2..9) {
say ("Fibonacci of k=#{k} order: ", (15+k).of { fibonacci_kth_order(_, k) })
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,490:
 
Faster algorithm:
<langsyntaxhighlight lang="ruby">func fibonacci_kth_order (n, k = 2) {
 
return 0 if (n < k-1)
Line 4,509:
for k in (2..9) {
say ("Fibonacci of k=#{k} order: ", (15+k).of { fibonacci_kth_order(_, k) })
}</langsyntaxhighlight>
(same output as above)
 
=={{header|Tailspin}}==
<langsyntaxhighlight lang="tailspin">
templates fibonacciNstep&{N:}
templates next
Line 4,543:
'
' -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,554:
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
proc fibber {args} {
Line 4,583:
print10 [fibber 1 1 2 4]
puts "LUCAS"
print10 [fibber 2 1]</langsyntaxhighlight>
{{out}}
<pre>
Line 4,597:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Option Explicit
 
Sub Main()
Line 4,658:
Next
Fibonacci_Step = R
End Function</langsyntaxhighlight>
 
{{Out}}
Line 4,667:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
'function arguments:
'init - initial series of the sequence(e.g. "1,1")
Line 4,699:
WScript.StdOut.Write "lucas: " & generate_seq("2,1",15)
WScript.StdOut.WriteLine
</syntaxhighlight>
</lang>
 
{{Out}}
Line 4,712:
{{trans|Visual Basic}}
{{works with|Visual Basic .NET|2011}}
<langsyntaxhighlight lang="vbnet">' Fibonacci n-step number sequences - VB.Net
Public Class FibonacciNstep
 
Line 4,749:
End Function 'FibonacciN
 
End Class 'FibonacciNstep</langsyntaxhighlight>
{{out}}
<pre>
Line 4,762:
=={{header|Vlang}}==
{{trans|Wren}}
<langsyntaxhighlight lang="vlang">fn fib_n(initial []int, num_terms int) []int {
n := initial.len
if n < 2 || num_terms < 0 {panic("Invalid argument(s).")}
Line 4,795:
println(values.map('${it:4}').join(' '))
}
}</langsyntaxhighlight>
 
{{out}}
Line 4,815:
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang="ecmascript">import "/fmt" for Fmt
 
var fibN = Fn.new { |initial, numTerms|
Line 4,844:
Fmt.write("$2d $-10s", i + 2, names[i])
Fmt.aprint(values, 4, 0, "")
}</langsyntaxhighlight>
 
{{out}}
Line 4,862:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
 
proc Nacci(N, F0); \Generate Fibonacci N-step sequence
Line 4,884:
Text(0, "Tetranacci: "); Nacci(4, [1, 1, 2, 4]);
Text(0, " Lucas: "); Nacci(2, [2, 1]);
]</langsyntaxhighlight>
 
Output:
Line 4,896:
=={{header|Yabasic}}==
{{trans|Lua}}
<langsyntaxhighlight Yabasiclang="yabasic">sub nStepFibs$(seq$, limit)
local iMax, sum, numb$(1), lim, i
Line 4,916:
print "Tribonacci:", nStepFibs$("1,1,2", 10)
print "Tetranacci:", nStepFibs$("1,1,2,4", 10)
print "Lucas:", nStepFibs$("2,1", 10)</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,927:
"%2d: ".fmt(ns.len()).print();
(N).pump(List,fibN(ns.xplode())).println();
}</langsyntaxhighlight>
{{out}}
<pre>
10,339

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.