Fibonacci sequence: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎{{header|Modula-3}}: added an iterative version)
m (FutureBasic entry moved out of the Basic group)
(369 intermediate revisions by more than 100 users not shown)
Line 38: Line 38:


=={{header|0815}}==
=={{header|0815}}==
<lang 0815>
<syntaxhighlight lang="0815">
%<:0D:>~$<:01:~%>=<:a94fad42221f2702:>~>
%<:0D:>~$<:01:~%>=<:a94fad42221f2702:>~>
}:_s:{x{={~$x+%{=>~>x~-x<:0D:~>~>~^:_s:?
}:_s:{x{={~$x+%{=>~>x~-x<:0D:~>~>~^:_s:?
</syntaxhighlight>
</lang>

=={{header|11l}}==
{{trans|Python}}

<syntaxhighlight lang="11l">F fib_iter(n)
I n < 2
R n
V fib_prev = 1
V fib = 1
L 2 .< n
(fib_prev, fib) = (fib, fib + fib_prev)
R fib

L(i) 1..20
print(fib_iter(i), end' ‘ ’)
print()</syntaxhighlight>

{{out}}
<pre>
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
</pre>


=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
For maximum compatibility, programs use only the basic instruction set.
For maximum compatibility, programs use only the basic instruction set.
===using fullword integers===
===using fullword integers===
<lang 360asm>* Fibonacci sequence 05/11/2014
<syntaxhighlight lang="360asm">* Fibonacci sequence 05/11/2014
* integer (31 bits) = 10 decimals -> max fibo(46)
* integer (31 bits) = 10 decimals -> max fibo(46)
FIBONACC CSECT
FIBONACC CSECT
Line 96: Line 117:
WTOBUF DC CL80'fibo(12)=1234567890'
WTOBUF DC CL80'fibo(12)=1234567890'
REGEQU
REGEQU
END FIBONACC</lang>
END FIBONACC</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 108: Line 129:
</pre>
</pre>
===using packed decimals===
===using packed decimals===
<lang 360asm>* Fibonacci sequence 31/07/2018
<syntaxhighlight lang="360asm">* Fibonacci sequence 31/07/2018
* packed dec (PL8) = 15 decimals => max fibo(73)
* packed dec (PL8) = 15 decimals => max fibo(73)
FIBOWTOP CSECT
FIBOWTOP CSECT
Line 155: Line 176:
WTOBUF DC CL80'fibo(12)=123456789012345 '
WTOBUF DC CL80'fibo(12)=123456789012345 '
REGEQU
REGEQU
END FIBOWTOP</lang>
END FIBOWTOP</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 171: Line 192:


The results are calculated and stored, but are not output to the screen or any other physical device: how to do that would depend on the hardware and the operating system.
The results are calculated and stored, but are not output to the screen or any other physical device: how to do that would depend on the hardware and the operating system.
<lang 6502asm> LDA #0
<syntaxhighlight lang="6502asm"> LDA #0
STA $F0 ; LOWER NUMBER
STA $F0 ; LOWER NUMBER
LDA #1
LDA #1
Line 186: Line 207:
CPX #$0A ; STOP AT FIB(10)
CPX #$0A ; STOP AT FIB(10)
BMI LOOP
BMI LOOP
RTS ; RETURN FROM SUBROUTINE</lang>
RTS ; RETURN FROM SUBROUTINE</syntaxhighlight>

=={{header|68000 Assembly}}==
{{trans|ARM Assembly}}
Input is in D0, and the output is also in D0. There is no protection from 32-bit overflow, so use at your own risk. (I used this [https://godbolt.org/ C compiler] to create this in ARM Assembly and translated it manually into 68000 Assembly. It wasn't that difficult since both CPUs have similar architectures.)
<syntaxhighlight lang="68000devpac">fib:
MOVEM.L D4-D5,-(SP)
MOVE.L D0,D4
MOVEQ #0,D5
CMP.L #2,D0
BCS .bar
MOVEQ #0,D5
.foo:
MOVE.L D4,D0
SUBQ.L #1,D0
JSR fib
SUBQ.L #2,D4
ADD.L D0,D5
CMP.L #1,D4
BHI .foo
.bar:
MOVE.L D5,D0
ADD.L D4,D0
MOVEM.L (SP)+,D4-D5
RTS</syntaxhighlight>


=={{header|8080 Assembly}}==
=={{header|8080 Assembly}}==
This subroutine expects to be called with the value of <math>n</math> in register <tt>A</tt>, and returns <math>f(n)</math> also in <tt>A</tt>. You may want to take steps to save the previous contents of <tt>B</tt>, <tt>C</tt>, and <tt>D</tt>. The routine only works with fairly small values of <math>n</math>.
This subroutine expects to be called with the value of <math>n</math> in register <tt>A</tt>, and returns <math>f(n)</math> also in <tt>A</tt>. You may want to take steps to save the previous contents of <tt>B</tt>, <tt>C</tt>, and <tt>D</tt>. The routine only works with fairly small values of <math>n</math>.
<lang 8080asm>FIBNCI: MOV C, A ; C will store the counter
<syntaxhighlight lang="8080asm">FIBNCI: MOV C, A ; C will store the counter
DCR C ; decrement, because we know f(1) already
DCR C ; decrement, because we know f(1) already
MVI A, 1
MVI A, 1
Line 199: Line 244:
DCR C
DCR C
JNZ LOOP ; jump if not zero
JNZ LOOP ; jump if not zero
RET ; return from subroutine</lang>
RET ; return from subroutine</syntaxhighlight>
The range may be easily be extended from the 13th (=233) to the 24th (=46368) Fibonacci number with 16-bit addition using DAD. The code here assumes the CP/M operating system.
<syntaxhighlight>
;-------------------------------------------------------
; useful equates
;-------------------------------------------------------
bdos equ 5 ; BDOS entry
cr equ 13 ; ASCII carriage return
lf equ 10 ; ASCII line feed
space equ 32 ; ASCII space char
conout equ 2 ; BDOS console output function
putstr equ 9 ; BDOS print string function
nterms equ 20 ; number of terms (max=24) to display
;-------------------------------------------------------
; main code begins here
;-------------------------------------------------------
org 100h
lxi h,0 ; save CP/M's stack
dad sp
shld oldstk
lxi sp,stack ; set our own stack
lxi d,signon ; print signon message
mvi c,putstr
call bdos
mvi a,0 ; start with Fib(0)
mloop: push a ; save our count
call fib
call putdec
mvi a,space ; separate the numbers
call putchr
pop a ; get our count back
inr a ; increment it
cpi nterms+1 ; have we reached our limit?
jnz mloop ; no, keep going
lhld oldstk ; all done; get CP/M's stack back
sphl ; restore it
ret ; back to command processor
;-------------------------------------------------------
; calculate nth Fibonacci number (max n = 24)
; entry: A = n
; exit: HL = Fib(n)
;-------------------------------------------------------
fib: mov c,a ; C holds n
lxi d,0 ; DE holds Fib(n-2)
lxi h,1 ; HL holds Fib(n-1)
ana a ; Fib(0) is a special case
jnz fib2 ; n > 0 so calculate normally
xchg ; otherwise return with HL=0
ret
fib2: dcr c
jz fib3 ; we're done
push h ; save Fib(n-1)
dad d ; HL = Fib(n), soon to be Fib(n-1)
pop d ; DE = old F(n-1), now Fib(n-2)
jmp fib2 ; ready for next pass
fib3: ret
;-------------------------------------------------------
; console output of char in A register
;-------------------------------------------------------
putchr: push h
push d
push b
mov e,a
mvi c,conout
call bdos
pop b
pop d
pop h
ret
;---------------------------------------------------------
; Output decimal number to console
; HL holds 16-bit unsigned binary number to print
;---------------------------------------------------------
putdec: push b
push d
push h
lxi b,-10
lxi d,-1
putdec2:
dad b
inx d
jc putdec2
lxi b,10
dad b
xchg
mov a,h
ora l
cnz putdec ; recursive call
mov a,e
adi '0'
call putchr
pop h
pop d
pop b
ret
;-------------------------------------------------------
; data area
;-------------------------------------------------------
signon: db 'Fibonacci number sequence:',cr,lf,'$'
oldstk: dw 0
stack equ $+128 ; 64-level stack
;
end
</syntaxhighlight>
{{out}}
<pre>
Fibonacci number sequence:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
</pre>

=={{header|8086 Assembly}}==
===Calculating the values at runtime===
Is it cheating to write it in C for 64-bit x86 then port it to 16-bit x86?

The max input is 24 before you start having 16-bit overflow.
<syntaxhighlight lang="asm">fib:
; WRITTEN IN C WITH X86-64 CLANG 3.3 AND DOWNGRADED TO 16-BIT X86
; INPUT: DI = THE NUMBER YOU WISH TO CALC THE FIBONACCI NUMBER FOR.
; OUTPUTS TO AX
push BP
push BX
push AX
mov BX, DI ;COPY INPUT TO BX
xor AX, AX ;MOV AX,0
test BX, BX ;SET FLAGS ACCORDING TO BX
je LBB0_4 ;IF BX == 0 RETURN 0
cmp BX, 1 ;IF BX == 1 RETURN 1
jne LBB0_3
mov AX, 1 ;ELSE, SET AX = 1 AND RETURN
jmp LBB0_4
LBB0_3:
lea DI, WORD PTR [BX - 1] ;DI = BX - 1
call fib ;RETURN FIB(BX-1)
mov BP, AX ;STORE THIS IN BP
add BX, -2
mov DI, BX
call fib ;GET FIB(DI - 2)
add AX, BP ;RETURN FIB(DI - 1) + FIB(DI - 2)
LBB0_4:

add sp,2
pop BX
pop BP
ret</syntaxhighlight>

===Using A Lookup Table===
With old computers it was common to use lookup tables to fetch pre-calculated values that would otherwise take some time to compute.
The elements of the table are ordered by index, so you can simply create a function that takes an offset as the parameter and returns
the element of the array at that offset.

Although lookup tables are very fast, there are some drawbacks to using them. For one, you end up taking up a lot of space. We're wasting a lot of bytes to store very low numbers at the beginning (each takes up 4 bytes regardless of how many digits you see). Unfortunately, when using lookup tables you have very little choice, since trying to conditionally change the scaling of the index would more than likely take more code than encoding all data as the maximum size regardless of the contents, as was done here. This keeps it simple for the CPU, which isn't aware of the intended size of each entry of the table.


For the purpose of this example, assume that both this code and the table are in the <code>.CODE</code> segment.
<syntaxhighlight lang="asm">getfib:
;input: BX = the desired fibonacci number (in other words, the "n" in "F(n)")
; DS must point to the segment where the fibonacci table is stored
;outputs to DX:AX (DX = high word, AX = low word)
push ds
cmp bx,41 ;bounds check
ja IndexOutOfBounds
shl bx,1
shl bx,1 ;multiply by 4, since this is a table of dwords
mov ax,@code
mov ds,ax
mov si,offset fib
mov ax,[ds:si] ;fetch the low word into AX
mov dx,2[ds:si] ;fetch the high word into DX
pop ds
ret


IndexOutOfBounds:
stc ;set carry to indicate an error
mov ax,0FFFFh ;return FFFF as the error code
pop ds
ret

;table of the first 41 fibonacci numbers
fib dword 0, 1, 1, 2, 3, 5, 8, 13
dword 21, 34, 55, 89, 144, 233, 377, 610
dword 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657
dword 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269
dword 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986
dword 102334155 </syntaxhighlight>


=={{header|8th}}==
=={{header|8th}}==
An iterative solution:
An iterative solution:
<lang forth>
<syntaxhighlight lang="forth">
: fibon \ n -- fib(n)
: fibon \ n -- fib(n)
>r 0 1
>r 0 1
Line 212: Line 442:
dup 1 n:= if 1 ;; then
dup 1 n:= if 1 ;; then
fibon nip ;
fibon nip ;
</syntaxhighlight>
</lang>


=={{header|ABAP}}==
=={{header|ABAP}}==
===Iterative===
===Iterative===
<lang ABAP>FORM fibonacci_iter USING index TYPE i
<syntaxhighlight lang="abap">FORM fibonacci_iter USING index TYPE i
CHANGING number_fib TYPE i.
CHANGING number_fib TYPE i.
DATA: lv_old type i,
DATA: lv_old type i,
Line 229: Line 459:
lv_cur = number_fib.
lv_cur = number_fib.
enddo.
enddo.
ENDFORM.</lang>
ENDFORM.</syntaxhighlight>


===Impure Functional===
===Impure Functional===
{{works with|ABAP|7.4 SP08 Or above only}}
{{works with|ABAP|7.4 SP08 Or above only}}
<lang ABAP>cl_demo_output=>display( REDUCE #( INIT fibnm = VALUE stringtab( ( |0| ) ( |1| ) )
<syntaxhighlight lang="abap">cl_demo_output=>display( REDUCE #( INIT fibnm = VALUE stringtab( ( |0| ) ( |1| ) )
n TYPE string
n TYPE string
x = `0`
x = `0`
Line 241: Line 471:
fibnm = VALUE #( BASE fibnm ( n ) )
fibnm = VALUE #( BASE fibnm ( n ) )
x = y
x = y
y = n ) ).</lang>
y = n ) ).</syntaxhighlight>


=={{header|ACL2}}==
=={{header|ACL2}}==
Fast, tail recursive solution:
Fast, tail recursive solution:
<lang Lisp>(defun fast-fib-r (n a b)
<syntaxhighlight lang="lisp">(defun fast-fib-r (n a b)
(if (or (zp n) (zp (1- n)))
(if (or (zp n) (zp (1- n)))
b
b
Line 261: Line 491:


(defun first-fibs (n)
(defun first-fibs (n)
(first-fibs-r n 0))</lang>
(first-fibs-r n 0))</syntaxhighlight>


{{out}}
{{out}}
Line 267: Line 497:
(1 1 2 3 5 8 13 21 34 55 89
(1 1 2 3 5 8 13 21 34 55 89
144 233 377 610 987 1597 2584 4181 6765)
144 233 377 610 987 1597 2584 4181 6765)
</pre>

=={{header|Action!}}==
Action! language does not support recursion. Therefore an iterative approach has been proposed.
<syntaxhighlight lang="action!">INT FUNC Fibonacci(INT n)
INT curr,prev,tmp

IF n>=-1 AND n<=1 THEN
RETURN (n)
FI

prev=0
IF n>0 THEN
curr=1
DO
tmp=prev
prev=curr
curr==+tmp
n==-1
UNTIL n=1
OD
ELSE
curr=-1
DO
tmp=prev
prev=curr
curr==+tmp
n==+1
UNTIL n=-1
OD
FI
RETURN (curr)

PROC Main()
BYTE n
INT f

Put(125) ;clear screen

FOR n=0 TO 22
DO
f=Fibonacci(n)
Position(2,n+1)
PrintF("Fib(%I)=%I",n,f)

IF n>0 THEN
f=Fibonacci(-n)
Position(21,n+1)
PrintF("Fib(%I)=%I",-n,f)
FI
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Fibonacci_sequence.png Screenshot from Atari 8-bit computer]
<pre>
Fib(0)=0
Fib(1)=1 Fib(-1)=-1
Fib(2)=1 Fib(-2)=-1
Fib(3)=2 Fib(-3)=-2
Fib(4)=3 Fib(-4)=-3
Fib(5)=5 Fib(-5)=-5
Fib(6)=8 Fib(-6)=-8
Fib(7)=13 Fib(-7)=-13
Fib(8)=21 Fib(-8)=-21
Fib(9)=34 Fib(-9)=-34
Fib(10)=55 Fib(-10)=-55
Fib(11)=89 Fib(-11)=-89
Fib(12)=144 Fib(-12)=-144
Fib(13)=233 Fib(-13)=-233
Fib(14)=377 Fib(-14)=-377
Fib(15)=610 Fib(-15)=-610
Fib(16)=987 Fib(-16)=-987
Fib(17)=1597 Fib(-17)=-1597
Fib(18)=2584 Fib(-18)=-2584
Fib(19)=4181 Fib(-19)=-4181
Fib(20)=6765 Fib(-20)=-6765
Fib(21)=10946 Fib(-21)=-10946
Fib(22)=17711 Fib(-22)=-17711
</pre>
</pre>


=={{header|ActionScript}}==
=={{header|ActionScript}}==
<lang actionscript>public function fib(n:uint):uint
<syntaxhighlight lang="actionscript">public function fib(n:uint):uint
{
{
if (n < 2)
if (n < 2)
Line 276: Line 584:
return fib(n - 1) + fib(n - 2);
return fib(n - 1) + fib(n - 2);
}</lang>
}</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==


===Recursive===
===Recursive===
<lang Ada>with Ada.Text_IO, Ada.Command_Line;
<syntaxhighlight lang="ada">with Ada.Text_IO, Ada.Command_Line;


procedure Fib is
procedure Fib is
Line 299: Line 607:
Ada.Text_IO.Put("Fibonacci(" & Integer'Image(X) & " ) = ");
Ada.Text_IO.Put("Fibonacci(" & Integer'Image(X) & " ) = ");
Ada.Text_IO.Put_Line(Integer'Image(Fib(X)));
Ada.Text_IO.Put_Line(Integer'Image(Fib(X)));
end Fib;</lang>
end Fib;</syntaxhighlight>


===Iterative, build-in integers===
===Iterative, build-in integers===
<lang ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;


procedure Test_Fibonacci is
procedure Test_Fibonacci is
Line 321: Line 629:
Put_Line (Positive'Image (Fibonacci (N)));
Put_Line (Positive'Image (Fibonacci (N)));
end loop;
end loop;
end Test_Fibonacci;</lang>
end Test_Fibonacci;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 341: Line 649:
Using the big integer implementation from a cryptographic library [https://github.com/cforler/Ada-Crypto-Library/].
Using the big integer implementation from a cryptographic library [https://github.com/cforler/Ada-Crypto-Library/].


<lang Ada>with Ada.Text_IO, Ada.Command_Line, Crypto.Types.Big_Numbers;
<syntaxhighlight lang="ada">with Ada.Text_IO, Ada.Command_Line, Crypto.Types.Big_Numbers;


procedure Fibonacci is
procedure Fibonacci is
Line 373: Line 681:
Ada.Text_IO.Put("Fibonacci(" & Integer'Image(X) & " ) = ");
Ada.Text_IO.Put("Fibonacci(" & Integer'Image(X) & " ) = ");
Ada.Text_IO.Put_Line(LN.Utils.To_String(Fib(X)));
Ada.Text_IO.Put_Line(LN.Utils.To_String(Fib(X)));
end Fibonacci;</lang>
end Fibonacci;</syntaxhighlight>


{{out}}
{{out}}
Line 379: Line 687:
Fibonacci( 777 ) = 1081213530912648191985419587942084110095342850438593857649766278346130479286685742885693301250359913460718567974798268702550329302771992851392180275594318434818082</pre>
Fibonacci( 777 ) = 1081213530912648191985419587942084110095342850438593857649766278346130479286685742885693301250359913460718567974798268702550329302771992851392180275594318434818082</pre>


===Fast method using fast matrix exponentiation===

<syntaxhighlight lang="ada">
with ada.text_io;
use ada.text_io;

procedure fast_fibo is
-- We work with biggest natural integers in a 64 bits machine
type Big_Int is mod 2**64;

-- We provide an index type for accessing the fibonacci sequence terms
type Index is new Big_Int;

-- fibo is a generic function that needs a modulus type since it will return
-- the n'th term of the fibonacci sequence modulus this type (use Big_Int to get the
-- expected behaviour in this particular task)
generic
type ring_element is mod <>;
with function "*" (a, b : ring_element) return ring_element is <>;
function fibo (n : Index) return ring_element;
function fibo (n : Index) return ring_element is

type matrix is array (1 .. 2, 1 .. 2) of ring_element;

-- f is the matrix you apply to a column containing (F_n, F_{n+1}) to get
-- the next one containing (F_{n+1},F_{n+2})
-- could be a more general matrix (given as a generic parameter) to deal with
-- other linear sequences of order 2
f : constant matrix := (1 => (0, 1), 2 => (1, 1));

function "*" (a, b : matrix) return matrix is
(1 => (a(1,1)*b(1,1)+a(1,2)*b(2,1), a(1,1)*b(1,2)+a(1,2)*b(2,2)),
2 => (a(2,1)*b(1,1)+a(2,2)*b(2,1), a(2,1)*b(1,2)+a(2,2)*b(2,2)));

function square (m : matrix) return matrix is (m * m);

-- Fast_Pow could be non recursive but it doesn't really matter since
-- the number of calls is bounded up by the size (in bits) of Big_Int (e.g 64)
function fast_pow (m : matrix; n : Index) return matrix is
(if n = 0 then (1 => (1, 0), 2 => (0, 1)) -- = identity matrix
elsif n mod 2 = 0 then square (fast_pow (m, n / 2))
else m * square (fast_pow (m, n / 2)));

begin
return fast_pow (f, n)(2, 1);
end fibo;

function Big_Int_Fibo is new fibo (Big_Int);
begin
-- calculate instantly F_n with n=10^15 (modulus 2^64 )
put_line (Big_Int_Fibo (10**15)'img);
end fast_fibo; </syntaxhighlight>


=={{header|AdvPL}}==
=={{header|AdvPL}}==
===Recursive===
===Recursive===
<syntaxhighlight lang="advpl">
<lang AdvPL>
#include "totvs.ch"
#include "totvs.ch"
User Function fibb(a,b,n)
User Function fibb(a,b,n)
return(if(--n>0,fibb(b,a+b,n),a))
return(if(--n>0,fibb(b,a+b,n),a))
</syntaxhighlight>
</lang>


===Iterative===
===Iterative===
<syntaxhighlight lang="advpl">
<lang AdvPL>
#include "totvs.ch"
#include "totvs.ch"
User Function fibb(n)
User Function fibb(n)
Line 399: Line 759:
end while
end while
return(fnext)
return(fnext)
</syntaxhighlight>
</lang>

=={{header|Agda}}==
<syntaxhighlight lang="agda">
module FibonacciSequence where

open import Data.Nat using (ℕ ; zero ; suc ; _+_)

rec_fib : (m : ℕ) -> (a : ℕ) -> (b : ℕ) -> ℕ
rec_fib zero a b = a
rec_fib (suc k) a b = rec_fib k b (a + b)

fib : (n : ℕ) -> ℕ
fib n = rec_fib n zero (suc zero)
</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>integer
<syntaxhighlight lang="aime">integer
fibs(integer n)
fibs(integer n)
{
{
Line 427: Line 801:
return w;
return w;
}
}
</syntaxhighlight>
</lang>

=={{header|ALGOL 60}}==
{{works with|A60}}
<syntaxhighlight lang="algol60">begin
comment Fibonacci sequence;
integer procedure fibonacci(n); value n; integer n;
begin
integer i, fn, fn1, fn2;
fn2 := 1;
fn1 := 0;
fn := 0;
for i := 1 step 1 until n do begin
fn := fn1 + fn2;
fn2 := fn1;
fn1 := fn
end;
fibonacci := fn
end fibonacci;
integer i;
for i := 0 step 1 until 20 do outinteger(1,fibonacci(i))
end </syntaxhighlight>
{{out}}
<pre>
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
</pre>



=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 435: Line 836:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<lang algol68>PROC analytic fibonacci = (LONG INT n)LONG INT:(
<syntaxhighlight lang="algol68">PROC analytic fibonacci = (LONG INT n)LONG INT:(
LONG REAL sqrt 5 = long sqrt(5);
LONG REAL sqrt 5 = long sqrt(5);
LONG REAL p = (1 + sqrt 5) / 2;
LONG REAL p = (1 + sqrt 5) / 2;
Line 447: Line 848:
print(", ")
print(", ")
OD;
OD;
print(new line)</lang>
print(new line)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 457: Line 858:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<lang algol68>PROC iterative fibonacci = (INT n)INT:
<syntaxhighlight lang="algol68">PROC iterative fibonacci = (INT n)INT:
CASE n+1 IN
CASE n+1 IN
0, 1, 1, 2, 3, 5
0, 1, 1, 2, 3, 5
Line 473: Line 874:
print(", ")
print(", ")
OD;
OD;
print(new line)</lang>
print(new line)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 482: Line 883:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<lang algol68>PROC recursive fibonacci = (INT n)INT:
<syntaxhighlight lang="algol68">PROC recursive fibonacci = (INT n)INT:
( n < 2 | n | fib(n-1) + fib(n-2));</lang>
( n < 2 | n | fib(n-1) + fib(n-2));</syntaxhighlight>
===Generative===
===Generative===
{{trans|Python|Note: This specimen retains the original [[Prime decomposition#Python|Python]] coding style.}}
{{trans|Python|Note: This specimen retains the original [[Prime decomposition#Python|Python]] coding style.}}
Line 489: Line 890:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<lang algol68>MODE YIELDINT = PROC(INT)VOID;
<syntaxhighlight lang="algol68">MODE YIELDINT = PROC(INT)VOID;


PROC gen fibonacci = (INT n, YIELDINT yield)VOID: (
PROC gen fibonacci = (INT n, YIELDINT yield)VOID: (
Line 506: Line 907:
# OD # ));
# OD # ));
print(new line)
print(new line)
)</lang>
)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 518: Line 919:


This uses a pre-generated list, requiring much less run-time processor usage, but assumes that INT is only 31 bits wide.
This uses a pre-generated list, requiring much less run-time processor usage, but assumes that INT is only 31 bits wide.
<lang algol68>[]INT const fibonacci = []INT( -1836311903, 1134903170,
<syntaxhighlight lang="algol68">[]INT const fibonacci = []INT( -1836311903, 1134903170,
-701408733, 433494437, -267914296, 165580141, -102334155,
-701408733, 433494437, -267914296, 165580141, -102334155,
63245986, -39088169, 24157817, -14930352, 9227465, -5702887,
63245986, -39088169, 24157817, -14930352, 9227465, -5702887,
Line 547: Line 948:
print(", ")
print(", ")
OD;
OD;
print(new line)</lang>
print(new line)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040
</pre>
</pre>

=={{header|ALGOL-M}}==
====Iterative====
<lang algol>INTEGER FUNCTION FIBONACCI( X ); INTEGER X;
BEGIN
INTEGER M, N, A, I;
M := 0;
N := 1;
FOR I := 2 STEP 1 UNTIL X DO
BEGIN
A := N;
N := M + N;
M := A;
END;
FIBONACCI := N;
END;</lang>

====Naively recursive====
<lang algol>INTEGER FUNCTION FIBONACCI( X ); INTEGER X;
BEGIN
IF X < 3 THEN
FIBONACCI := 1
ELSE
FIBONACCI := FIBONACCI( X - 2 ) + FIBONACCI( X - 1 );
END;</lang>


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
% return the nth Fibonacci number %
% return the nth Fibonacci number %
integer procedure Fibonacci( integer value n ) ;
integer procedure Fibonacci( integer value n ) ;
Line 597: Line 973:
for i := 0 until 10 do writeon( i_w := 3, s_w := 0, Fibonacci( i ) )
for i := 0 until 10 do writeon( i_w := 3, s_w := 0, Fibonacci( i ) )


end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
0 1 1 2 3 5 8 13 21 34 55
0 1 1 2 3 5 8 13 21 34 55
</pre>
</pre>

=={{header|ALGOL-M}}==
Note that the 21st Fibonacci number (= 10946) is the largest that can be calculated without overflowing ALGOL-M's integer data type.
====Iterative====
<syntaxhighlight lang="algol">INTEGER FUNCTION FIBONACCI( X ); INTEGER X;
BEGIN
INTEGER M, N, A, I;
M := 0;
N := 1;
FOR I := 2 STEP 1 UNTIL X DO
BEGIN
A := N;
N := M + N;
M := A;
END;
FIBONACCI := N;
END;</syntaxhighlight>

====Naively recursive====
<syntaxhighlight lang="algol">INTEGER FUNCTION FIBONACCI( X ); INTEGER X;
BEGIN
IF X < 3 THEN
FIBONACCI := 1
ELSE
FIBONACCI := FIBONACCI( X - 2 ) + FIBONACCI( X - 1 );
END;</syntaxhighlight>


=={{header|Alore}}==
=={{header|Alore}}==


<lang Alore>def fib(n as Int) as Int
<syntaxhighlight lang="alore">def fib(n as Int) as Int
if n < 2
if n < 2
return 1
return 1
end
end
return fib(n-1) + fib(n-2)
return fib(n-1) + fib(n-2)
end</lang>
end</syntaxhighlight>

=={{header|Amazing Hopper}}==
Analitic, Recursive and Iterative mode.
<syntaxhighlight lang="amazing hopper">
#include <hbasic.h>

#define TERM1 1.61803398874989
#define TERM2 -0.61803398874989

#context get Fibonacci number with analitic mode
GetArgs(n)
get Inv of (M_SQRT5), Mul by( Pow (TERM 1, n), Minus( Pow(TERM 2, n) ) );
then Return\\

#proto fibonacci_recursive(__X__)
#synon _fibonacci_recursive getFibonaccinumberwithrecursivemodeof

#proto fibonacci_iterative(__X__)
#synon _fibonacci_iterative getFibonaccinumberwithiterativemodeof

Begin
Option Stack 1024

get Arg Number(2, n), and Take( n );
then, get Fibonacci number with analitic mode, and Print It with a Newl.
secondly, get Fibonacci number with recursive mode of(n), and Print It with a Newl.
finally, get Fibonacci number with iterative mode of (n), and Print It with a Newl.
End

Subrutines

fibonacci_recursive(n)
Iif ( var(n) Is Le? (2), 1 , \
get Fibonacci number with recursive mode of( var(n) Minus (1));\
get Fibonacci number with recursive mode of( var(n) Minus (2)); and Add It )
Return

fibonacci_iterative(n)
A=0
B=1
For Up( I:=2, n, 1 )
C=B
Let ( B: = var(A) Plus (B) )
A=C
Next
Return(B)
</syntaxhighlight>
{{out}}
<pre>
$ hopper src/fibo1.bas 25
75025
75025
75025
</pre>


=={{header|AntLang}}==
=={{header|AntLang}}==
<lang AntLang>/Sequence
<syntaxhighlight lang="antlang">/Sequence
fib:{<0;1> {x,<x[-1]+x[-2]>}/ range[x]}
fib:{<0;1> {x,<x[-1]+x[-2]>}/ range[x]}
/nth
/nth
fibn:{fib[x][x]}</lang>
fibn:{fib[x][x]}</syntaxhighlight>


=={{header|Apex}}==
=={{header|Apex}}==


<syntaxhighlight lang="apex">
<lang Apex>
/*
/*
author: snugsfbay
author: snugsfbay
Line 664: Line 1,120:
}
}
</syntaxhighlight>
</lang>


=={{header|APL}}==
=={{header|APL}}==

====Naive Recursive====

{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">
fib←{⍵≤1:⍵ ⋄ (∇ ⍵-1)+∇ ⍵-2}
</syntaxhighlight>

Read this as: In the variable "fib", store the function that says, if the argument is less than or equal to 1, return the argument. Else, calculate the value you get when you recursively call the current function with the argument of the current argument minus one and add that to the value you get when you recursively call the current function with the argument of the current function minus two.

This naive solution requires Dyalog APL because GNU APL does not support this syntax for conditional guards.

====Array====
{{works with|Dyalog APL}}
{{works with|GNU APL}}

Since APL is an array language we'll use the following identity:
Since APL is an array language we'll use the following identity:
:<math>\begin{pmatrix} 1 & 1 \\ 1 & 0 \end{pmatrix}^n = \begin{pmatrix} F_{n+1} & F_n \\ F_n & F_{n-1} \end{pmatrix}.</math>
:<math>\begin{pmatrix} 1 & 1 \\ 1 & 0 \end{pmatrix}^n = \begin{pmatrix} F_{n+1} & F_n \\ F_n & F_{n-1} \end{pmatrix}.</math>
In APL:
In APL:
<syntaxhighlight lang="apl">
<lang APL>
↑+.×/N/⊂2 2⍴1 1 1 0
↑+.×/N/⊂2 2⍴1 1 1 0
</syntaxhighlight>
</lang>
Plugging in 4 for N gives the following result:
Plugging in 4 for N gives the following result:
:<math>\begin{pmatrix} 5 & 3 \\ 3 & 2 \end{pmatrix}</math>
:<math>\begin{pmatrix} 5 & 3 \\ 3 & 2 \end{pmatrix}</math>
Line 679: Line 1,151:
The ''First'' removes the shell from the ''Enclose''.
The ''First'' removes the shell from the ''Enclose''.
At this point we're basically done, but we need to pick out only <math>F_n</math> in order to complete the task. Here's one way:
At this point we're basically done, but we need to pick out only <math>F_n</math> in order to complete the task. Here's one way:
<syntaxhighlight lang="apl">
<lang APL>
↑0 1↓↑+.×/N/⊂2 2⍴1 1 1 0
↑0 1↓↑+.×/N/⊂2 2⍴1 1 1 0
</syntaxhighlight>
</lang>


===Analytic===
====Analytic====
{{works with|Dyalog APL}}
{{works with|GNU APL}}
An alternative approach, using Binet's formula (which was apparently known long before Binet):
An alternative approach, using Binet's formula (which was apparently known long before Binet):
<lang apl>⌊.5+(((1+PHI)÷2)*⍳N)÷PHI←5*.5</lang>
<syntaxhighlight lang="apl">⌊.5+(((1+PHI)÷2)*⍳N)÷PHI←5*.5</syntaxhighlight>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
Line 692: Line 1,166:
===Imperative===
===Imperative===


<lang applescript>set fibs to {}
<syntaxhighlight lang="applescript">set fibs to {}
set x to (text returned of (display dialog "What fibbonaci number do you want?" default answer "3"))
set x to (text returned of (display dialog "What fibbonaci number do you want?" default answer "3"))
set x to x as integer
set x to x as integer
Line 702: Line 1,176:
end if
end if
end repeat
end repeat
return item x of fibs</lang>
return item x of fibs</syntaxhighlight>




Line 710: Line 1,184:
The simple recursive version is famously slow:
The simple recursive version is famously slow:


<lang AppleScript>on fib(n)
<syntaxhighlight lang="applescript">on fib(n)
if n < 1 then
if n < 1 then
0
0
Line 718: Line 1,192:
fib(n - 2) + fib(n - 1)
fib(n - 2) + fib(n - 1)
end if
end if
end fib</lang>
end fib</syntaxhighlight>


but we can combine '''enumFromTo(m, n)''' with the accumulator of a higher-order '''fold/reduce''' function to memoize the series:
but we can combine '''enumFromTo(m, n)''' with the accumulator of a higher-order '''fold/reduce''' function to memoize the series:
Line 724: Line 1,198:
{{Trans|JavaScript}} (ES6 memoized fold example)
{{Trans|JavaScript}} (ES6 memoized fold example)
{{Trans|Haskell}} (Memoized fold example)
{{Trans|Haskell}} (Memoized fold example)
<syntaxhighlight lang="applescript">-------------------- FIBONACCI SEQUENCE --------------------
<lang AppleScript>-- fib :: Int -> Int

-- fib :: Int -> Int
on fib(n)
on fib(n)
Line 738: Line 1,214:




-- TEST -----------------------------------------------------------------------
--------------------------- TEST ---------------------------
on run
on run
Line 746: Line 1,222:
end run
end run


-- GENERIC FUNCTIONS ----------------------------------------------------------
-------------------- GENERIC FUNCTIONS ---------------------


-- enumFromTo :: Int -> Int -> [Int]
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
on enumFromTo(m, n)
if n < m then
if m n then
set d to -1
set lst to {}
repeat with i from m to n
set end of lst to i
end repeat
lst
else
else
set d to 1
{}
end if
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
end enumFromTo


Line 784: Line 1,259:
end script
end script
end if
end if
end mReturn</lang>
end mReturn</syntaxhighlight>
{{Out}}
{{Out}}
<pre>2178309</pre>
<pre>2178309</pre>
Line 804: Line 1,279:
=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
Expects to be called with <math>n</math> in R0, and will return <math>f(n)</math> in the same register.
Expects to be called with <math>n</math> in R0, and will return <math>f(n)</math> in the same register.
<lang armasm>fibonacci:
<syntaxhighlight lang="armasm">fibonacci:
push {r1-r3}
push {r1-r3}
mov r1, #0
mov r1, #0
Line 819: Line 1,294:
mov r0, r2
mov r0, r2
pop {r1-r3}
pop {r1-r3}
mov pc, lr</lang>
mov pc, lr</syntaxhighlight>


=={{header|ArnoldC}}==
=={{header|ArnoldC}}==


<lang ArnoldC>IT'S SHOWTIME
<syntaxhighlight lang="arnoldc">IT'S SHOWTIME


HEY CHRISTMAS TREE f1
HEY CHRISTMAS TREE f1
Line 853: Line 1,328:
CHILL
CHILL


YOU HAVE BEEN TERMINATED</lang>
YOU HAVE BEEN TERMINATED</syntaxhighlight>

=={{header|Arturo}}==

===Recursive===

<syntaxhighlight lang="arturo">fib: $[x][
if? x<2 [1]
else [(fib x-1) + (fib x-2)]
]

loop 1..25 [x][
print ["Fibonacci of" x "=" fib x]
]</syntaxhighlight>


=={{header|AsciiDots}}==
=={{header|AsciiDots}}==


<syntaxhighlight lang="asciidots">
<lang AsciiDots>


/--#$--\
/--#$--\
Line 869: Line 1,357:
. .
. .


</syntaxhighlight>
</lang>


=={{header|ATS}}==
=={{header|ATS}}==
===Recursive===
===Recursive===
<syntaxhighlight lang="ats">
<lang ATS>
fun fib_rec(n: int): int =
fun fib_rec(n: int): int =
if n >= 2 then fib_rec(n-1) + fib_rec(n-2) else n
if n >= 2 then fib_rec(n-1) + fib_rec(n-2) else n
</syntaxhighlight>
</lang>


===Iterative===
===Iterative===
<syntaxhighlight lang="ats">
<lang ATS>
(*
(*
** This one is also referred to as being tail-recursive
** This one is also referred to as being tail-recursive
Line 889: Line 1,377:
then (fix loop (i:int, r0:int, r1:int): int => if i > 1 then loop (i-1, r1, r0+r1) else r1)(n, 0, 1)
then (fix loop (i:int, r0:int, r1:int): int => if i > 1 then loop (i-1, r1, r0+r1) else r1)(n, 0, 1)
else 0
else 0
</syntaxhighlight>
</lang>


===Iterative and Verified===
===Iterative and Verified===
<syntaxhighlight lang="ats">
<lang ATS>
(*
(*
** This implementation is verified!
** This implementation is verified!
Line 920: Line 1,408:
loop {0} (FIB0 (), FIB1 () | n, 0, 1)
loop {0} (FIB0 (), FIB1 () | n, 0, 1)
end // end of [fibats]
end // end of [fibats]
</syntaxhighlight>
</lang>


===Matrix-based===
===Matrix-based===
<syntaxhighlight lang="ats">
<lang ATS>
(* ****** ****** *)
(* ****** ****** *)
//
//
Line 1,003: Line 1,491:
//
//
} (* end of [main0] *)
} (* end of [main0] *)
</syntaxhighlight>
</lang>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
Line 1,010: Line 1,498:
===Iterative===
===Iterative===
{{trans|C}}
{{trans|C}}
<lang AutoHotkey>Loop, 5
<syntaxhighlight lang="autohotkey">Loop, 5
MsgBox % fib(A_Index)
MsgBox % fib(A_Index)
Return
Return
Line 1,027: Line 1,515:
}
}
Return this
Return this
}</lang>
}</syntaxhighlight>


===Recursive and iterative===
===Recursive and iterative===
Source: [http://www.autohotkey.com/forum/topic44657.html AutoHotkey forum] by Laszlo
Source: [http://www.autohotkey.com/forum/topic44657.html AutoHotkey forum] by Laszlo
<syntaxhighlight lang="autohotkey">/*
<lang AutoHotkey>/*
Important note: the recursive version would be very slow
Important note: the recursive version would be very slow
without a global or static array. The iterative version
without a global or static array. The iterative version
Line 1,047: Line 1,535:
c := b, b += a, a := c
c := b, b += a, a := c
Return n=0 ? 0 : n>0 || n&1 ? b : -b
Return n=0 ? 0 : n>0 || n&1 ? b : -b
}</lang>
}</syntaxhighlight>

=={{header|AutoIt}}==
=={{header|AutoIt}}==
===Iterative===
===Iterative===
<lang AutoIt>#AutoIt Version: 3.2.10.0
<syntaxhighlight lang="autoit">#AutoIt Version: 3.2.10.0
$n0 = 0
$n0 = 0
$n1 = 1
$n1 = 1
Line 1,077: Line 1,566:
Return $febo
Return $febo
EndFunc
EndFunc
</syntaxhighlight>
</lang>
===Recursive===
===Recursive===
<lang AutoIt>#AutoIt Version: 3.2.10.0
<syntaxhighlight lang="autoit">#AutoIt Version: 3.2.10.0
$n0 = 0
$n0 = 0
$n1 = 1
$n1 = 1
Line 1,098: Line 1,587:
EndIf
EndIf
EndFunc
EndFunc
</syntaxhighlight>
</lang>


=={{header|AWK}}==
=={{header|AWK}}==
As in many examples, this one-liner contains the function as well as testing with input from stdin, output to stdout.
As in many examples, this one-liner contains the function as well as testing with input from stdin, output to stdout.
<lang awk>$ awk 'func fib(n){return(n<2?n:fib(n-1)+fib(n-2))}{print "fib("$1")="fib($1)}'
<syntaxhighlight lang="awk">$ awk 'func fib(n){return(n<2?n:fib(n-1)+fib(n-2))}{print "fib("$1")="fib($1)}'
10
10
fib(10)=55</lang>
fib(10)=55</syntaxhighlight>


=={{header|Axe}}==
=={{header|Axe}}==
Line 1,111: Line 1,600:


Iterative solution:
Iterative solution:
<lang axe>Lbl FIB
<syntaxhighlight lang="axe">Lbl FIB
r₁→N
r₁→N
0→I
0→I
Line 1,121: Line 1,610:
End
End
J
J
Return</lang>
Return</syntaxhighlight>


=={{header|Babel}}==
In Babel, we can define fib using a stack-based approach that is not recursive:

<syntaxhighlight lang="babel">fib { <- 0 1 { dup <- + -> swap } -> times zap } <</syntaxhighlight>

foo x < puts x in foo. In this case, x is the code list between the curly-braces. This is how you define callable code in Babel. The definition works by initializing the stack with 0, 1. On each iteration of the times loop, the function duplicates the top element. In the first iteration, this gives 0, 1, 1. Then it moves down the stack with the <- operator, giving 0, 1 again. It adds, giving 1. then it moves back up the stack, giving 1, 1. Then it swaps. On the next iteration this gives:

<pre>1, 1, 1 (dup)
1, 1, (<-)
2 (+)
2, 1 (->)
1, 2 (swap) </pre>

And so on. To test fib:

<syntaxhighlight lang="babel">{19 iter - fib !} 20 times collect ! lsnum !</syntaxhighlight>

{{out}}
<pre>( 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 )</pre>


=={{header|bash}}==
=={{header|bash}}==
===Iterative===
===Iterative===
<lang bash>
<syntaxhighlight lang="bash">
$ fib=1;j=1;while((fib<100));do echo $fib;((k=fib+j,fib=j,j=k));done
$ fib=1;j=1;while((fib<100));do echo $fib;((k=fib+j,fib=j,j=k));done
</syntaxhighlight>
</lang>
<pre>
<pre>
1
1
Line 1,144: Line 1,652:


===Recursive===
===Recursive===
<lang bash>fib()
<syntaxhighlight lang="bash">fib()
{
{
if [ $1 -le 0 ]
if [ $1 -le 0 ]
Line 1,160: Line 1,668:
fi
fi
}
}
</syntaxhighlight>
</lang>


=={{header|Babel}}==
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
In Babel, we can define fib using a stack-based approach that is not recursive:
Same code as [[#Commodore_BASIC|Commodore BASIC]]


Entering a value of N > 183, produces an error message:
<lang babel>fib { <- 0 1 { dup <- + -> swap } -> times zap } <</lang>
<pre>?OVERFLOW ERROR IN 220</pre>


==={{header|BASIC256}}===
foo x < puts x in foo. In this case, x is the code list between the curly-braces. This is how you define callable code in Babel. The definition works by initializing the stack with 0, 1. On each iteration of the times loop, the function duplicates the top element. In the first iteration, this gives 0, 1, 1. Then it moves down the stack with the <- operator, giving 0, 1 again. It adds, giving 1. then it moves back up the stack, giving 1, 1. Then it swaps. On the next iteration this gives:
<syntaxhighlight lang="basic256">
# Basic-256 ver 1.1.4
# iterative Fibonacci sequence
# Matches sequence A000045 in the OEIS, https://oeis.org/A000045/list


# Return the Nth Fibonacci number
<pre>1, 1, 1 (dup)
1, 1, (<-)
2 (+)
2, 1 (->)
1, 2 (swap) </pre>


input "N = ",f
And so on. To test fib:
limit = 500 # set upper limit - can be changed, removed
f = int(f)
if f > limit then f = limit
a = 0 : b = 1 : c = 0 : n = 0 # initial values


<lang babel>{19 iter - fib !} 20 times collect ! lsnum !</lang>


while n < f
print n + chr(9) + c # chr(9) = tab
a = b
b = c
c = a + b
n += 1
end while

print " "
print n + chr(9) + c
</syntaxhighlight>

==={{header|BBC BASIC}}===
<syntaxhighlight lang="bbcbasic"> PRINT FNfibonacci_r(1), FNfibonacci_i(1)
PRINT FNfibonacci_r(13), FNfibonacci_i(13)
PRINT FNfibonacci_r(26), FNfibonacci_i(26)
END
DEF FNfibonacci_r(N)
IF N < 2 THEN = N
= FNfibonacci_r(N-1) + FNfibonacci_r(N-2)
DEF FNfibonacci_i(N)
LOCAL F, I, P, T
IF N < 2 THEN = N
P = 1
FOR I = 1 TO N
T = F
F += P
P = T
NEXT
= F
</syntaxhighlight>
{{out}}
{{out}}
<pre>( 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 )</pre>
<pre> 1 1
233 233
121393 121393</pre>
==={{header|bootBASIC}}===
Variables in bootBASIC are 2 byte unsigned integers that roll over if there is an overflow. Entering a number greater than 24 will result in an incorrect outcome.
<syntaxhighlight lang="BASIC">
10 print "Enter a ";
20 print "number ";
30 print "greater ";
40 print "than 1";
50 print " and less";
60 print " than 25";
70 input z
80 b=1
90 a=0
100 n=2
110 f=a+b
120 a=b
130 b=f
140 n=n+1
150 if n-z-1 goto 110
160 print "The ";
170 print z ;
180 print "th ";
190 print "Fibonacci ";
200 print "Number is ";
210 print f
</syntaxhighlight>


=={{header|BASIC}}==
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="qbasic">100 cls
110 for i = 0 to 20 : print fibor(i); : next i
120 print
130 for i = 0 to 20 : print fiboi(i); : next i
140 print
150 for i = 0 to 20 : print fiboa(i); : next i
160 end
170 sub fibor(n) : 'Recursive
180 if n < 2 then
190 fibor = n
200 else
210 fibor = fibor(n-1)+fibor(n-2)
220 endif
230 end sub
240 sub fiboi(n) : 'Iterative
250 n1 = 0
260 n2 = 1
270 for k = 1 to abs(n)
280 sum = n1+n2
290 n1 = n2
300 n2 = sum
310 next k
320 if n < 0 then
330 fiboi = n1*((-1)^((-n)+1))
340 else
350 fiboi = n1
360 endif
370 end sub
380 sub fiboa(n) : 'Analytic
390 fiboa = int(0.5+(((sqr 5+1)/2)^n)/sqr 5)
400 end sub</syntaxhighlight>
{{out}}
<pre>0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765</pre>

==={{header|Commodore BASIC}}===
<syntaxhighlight lang="basic">100 PRINT CHR$(147); CHR$(18); "**** FIBONACCI GENERATOR ****"
110 INPUT "MIN, MAX"; N1, N2
120 IF N1 > N2 THEN T = N1: N1 = N2: N2 = T
130 A = 0: B = 1: S = SGN(N1)
140 FOR I = S TO N1 STEP S
150 : IF S > 0 THEN T = A + B: A = B: B = T
160 : IF S < 0 THEN T = B - A: B = A: A = T
170 NEXT I
180 PRINT
190 PRINT STR$(A); : REM STR$() PREVENTS TRAILING SPACE
200 IF N2 = N1 THEN 250
210 FOR I = N1 + 1 TO N2
220 : T = A + B: A = B: B = T
230 : PRINT ","; STR$(A);
240 NEXT I
250 PRINT</syntaxhighlight>

{{Out}}
<pre>**** FIBONACCI GENERATOR ****

MIN, MAX? -6,6

-8, 5,-3, 2,-1, 1, 0, 1, 1, 2, 3, 5, 8

READY.</pre>

==={{header|Craft Basic}}===
<syntaxhighlight lang="basic">let a = 1
let b = 1

print "Fibonacci Sequence"

for i = 0 to 20

let s = a + b
let a = b
let b = s

print s

next i</syntaxhighlight>
{{out| Output}}<pre>Fibonacci Sequence
2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 </pre>

==={{header|FreeBASIC}}===
Extended sequence coded big integer.
<syntaxhighlight lang="freebasic">'Fibonacci extended
'Freebasic version 24 Windows
Dim Shared ADDQmod(0 To 19) As Ubyte
Dim Shared ADDbool(0 To 19) As Ubyte

For z As Integer=0 To 19
ADDQmod(z)=(z Mod 10+48)
ADDbool(z)=(-(10<=z))
Next z

Function plusINT(NUM1 As String,NUM2 As String) As String
Dim As Byte flag
#macro finish()
three=Ltrim(three,"0")
If three="" Then Return "0"
If flag=1 Then Swap NUM2,NUM1
Return three
Exit Function
#endmacro
var lenf=Len(NUM1)
var lens=Len(NUM2)
If lens>lenf Then
Swap NUM2,NUM1
Swap lens,lenf
flag=1
End If
var diff=lenf-lens-Sgn(lenf-lens)
var three="0"+NUM1
var two=String(lenf-lens,"0")+NUM2
Dim As Integer n2
Dim As Ubyte addup,addcarry
addcarry=0
For n2=lenf-1 To diff Step -1
addup=two[n2]+NUM1[n2]-96
three[n2+1]=addQmod(addup+addcarry)
addcarry=addbool(addup+addcarry)
Next n2
If addcarry=0 Then
finish()
End If
If n2=-1 Then
three[0]=addcarry+48
finish()
End If
For n2=n2 To 0 Step -1
addup=two[n2]+NUM1[n2]-96
three[n2+1]=addQmod(addup+addcarry)
addcarry=addbool(addup+addcarry)
Next n2
three[0]=addcarry+48
finish()
End Function

Function fibonacci(n As Integer) As String
Dim As String sl,l,term
sl="0": l="1"
If n=1 Then Return "0"
If n=2 Then Return "1"
n=n-2
For x As Integer= 1 To n
term=plusINT(l,sl)
sl=l
l=term
Next x
Function =term
End Function

'============== EXAMPLE ===============
print "THE SEQUENCE TO 10:"
print
For n As Integer=1 To 10
Print "term";n;": "; fibonacci(n)
Next n
print
print "Selected Fibonacci number"
print "Fibonacci 500"
print
print fibonacci(500)
Sleep</syntaxhighlight>
{{out}}
<pre>THE SEQUENCE TO 10:

term 1: 0
term 2: 1
term 3: 1
term 4: 2
term 5: 3
term 6: 5
term 7: 8
term 8: 13
term 9: 21
term 10: 34

Selected Fibonacci number
Fibonacci 500

86168291600238450732788312165664788095941068326060883324529903470149056115823592
713458328176574447204501</pre>

==={{header|FTCBASIC}}===
<syntaxhighlight lang="basic">define a = 1, b = 1, s = 0, i = 0

cls

print "Fibonacci Sequence"

do

let s = a + b
let a = b
let b = s
+1 i

print s

loop i < 20

pause
end</syntaxhighlight>


==={{header|GFA Basic}}===
<syntaxhighlight lang="text">
'
' Compute nth Fibonacci number
'
' open a window for display
OPENW 1
CLEARW 1
' Display some fibonacci numbers
' Fib(46) is the largest number GFA Basic can reach
' (long integers are 4 bytes)
FOR i%=0 TO 46
PRINT "fib(";i%;")=";@fib(i%)
NEXT i%
' wait for a key press and tidy up
~INP(2)
CLOSEW 1
'
' Function to compute nth fibonacci number
' n must be in range 0 to 46, inclusive
'
FUNCTION fib(n%)
LOCAL n0%,n1%,nn%,i%
n0%=0
n1%=1
SELECT n%
CASE 0
RETURN n0%
CASE 1
RETURN n1%
DEFAULT
FOR i%=2 TO n%
nn%=n0%+n1%
n0%=n1%
n1%=nn%
NEXT i%
RETURN nn%
ENDSELECT
ENDFUNC
</syntaxhighlight>

==={{header|GW-BASIC}}===
{{works with|BASICA}}
====Iterative====
<syntaxhighlight lang="gwbasic">
10 ' SAVE"FIBONA", A
20 ' Secuencia de Fibonacci
30 ' Var
40 DEFDBL D
50 IMAXFIBO% = 76
60 DNUM1 = 1: DNUM2 = DNUM1
70 CLS
80 PRINT "Este programa calcula la serie de Fibonacci."
90 PRINT DNUM1; DNUM2;
100 FOR I% = 1 TO IMAXFIBO%
110 DNUM3 = DNUM1 + DNUM2
120 PRINT DNUM3;
130 DNUM1 = DNUM2: DNUM2 = DNUM3
140 NEXT I%
150 PRINT
160 PRINT "Fin de la ejecución del programa."
170 END
</syntaxhighlight>
{{out}}
<pre>
Este programa calcula la serie de Fibonacci.
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584
4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229
832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817
39088169 63245986 102334155 165580141 267914296 433494437 701408733
1134903170 1836311903 2971215073 4807526976 7778742049 12586269025
20365011074 32951280099 53316291173 86267571272 139583862445 225851433717
365435296162 591286729879 956722026041 1548008755920 2504730781961
4052739537881 6557470319842 10610209857723 17167680177565 27777890035288
44945570212853 72723460248141 117669030460994 190392490709135
308061521170129 498454011879264 806515533049393 1304969544928657
2111485077978050 3416454622906707 5527939700884757 8944394323791464
Fin de la ejecución del programa.
Ok
</pre>

====Binet formula====
<syntaxhighlight lang="gwbasic">
10 ' SAVE"FIBINF", A
20 ' Secuencia de Fibonacci mediante la fórmula de Binet
30 ' Var
40 DEFDBL D
50 IMAXFIBO% = 77
60 DSQR5 = SQR(5)
70 DPIV1 = (1 + DSQR5) / 2
80 DPIV2 = (1 - DSQR5) / 2
90 DNUM1 = DPIV1: DNUM2 = DPIV2
100 CLS
110 PRINT "Este programa calcula la serie de Fibonacci."
120 FOR I% = 1 TO IMAXFIBO%
130 DNUM1 = DNUM1 * DPIV1
140 DNUM2 = DNUM2 * DPIV2
150 PRINT FIX(((DNUM1 - DNUM2) / DSQR5)+.5);
160 NEXT I%
170 PRINT
180 PRINT "Fin de la ejecución del programa."
190 END
</syntaxhighlight>
{{out}}
<pre>
Este programa calcula la serie de Fibonacci.
1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
6765 10946 17711 28657 46368 75025 121393 196418 317811 514229
832040 1346269 2178310 3524579 5702889 9227468 14930357 24157826
39088183 63246010 102334195 165580207 267914406 433494620 701409036
1134903671 1836312733 2971216446 4807529247 7778745802 12586275225
20365021312 32951296999 53316319058 86267617266 139583938281 225851558714
365435502118 591287069122 956722584654 1548009675479 2504732295250
4052742027550 6557474414738 10610216591046 17167691246479 27777908226979
44945600103607 72723509350188 117669111103547 190392623123089
308061738545741 498454368657289 806516118510594 1304970505463907
2111486653578091 3416457206941612 5527943938022908 8944401270367342
Fin de la ejecución del programa.
Ok 
</pre>

==={{header|Integer BASIC}}===
Only works with quite small values of <math>n</math>.
<syntaxhighlight lang="basic"> 10 INPUT N
20 A=0
30 B=1
40 FOR I=2 TO N
50 C=B
60 B=A+B
70 A=C
80 NEXT I
90 PRINT B
100 END</syntaxhighlight>

==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">100 PROGRAM "Fibonac.bas"
110 FOR I=0 TO 20
120 PRINT "F";I,FIB(I)
130 NEXT
140 DEF FIB(N)
150 NUMERIC I
160 LET A=0:LET B=1
170 FOR I=1 TO N
180 LET T=A+B:LET A=B:LET B=T
190 NEXT
200 LET FIB=A
210 END DEF</syntaxhighlight>

==={{header|Liberty BASIC}}===
====Iterative/Recursive====
{{works with|Just BASIC}}
<syntaxhighlight lang="lb">
for i = 0 to 15
print fiboR(i),fiboI(i)
next i
function fiboR(n)
if n <= 1 then
fiboR = n
else
fiboR = fiboR(n-1) + fiboR(n-2)
end if
end function
function fiboI(n)
a = 0
b = 1
for i = 1 to n
temp = a + b
a = b
b = temp
next i
fiboI = a
end function
</syntaxhighlight>
{{out}}
<pre>
0 0
1 1
1 1
2 2
3 3
5 5
8 8
13 13
21 21
34 34
55 55
89 89
144 144
233 233
377 377
610 610
</pre>
====Iterative/Negative====
{{works with|Just BASIC}}
<syntaxhighlight lang="lb">
print "Rosetta Code - Fibonacci sequence": print
print " n Fn"
for x=-12 to 12 '68 max
print using("### ", x); using("##############", FibonacciTerm(x))
next x
print
[start]
input "Enter a term#: "; n$
n$=lower$(trim$(n$))
if n$="" then print "Program complete.": end
print FibonacciTerm(val(n$))
goto [start]

function FibonacciTerm(n)
n=int(n)
FTa=0: FTb=1: FTc=-1
select case
case n=0 : FibonacciTerm=0 : exit function
case n=1 : FibonacciTerm=1 : exit function
case n=-1 : FibonacciTerm=-1 : exit function
case n>1
for x=2 to n
FibonacciTerm=FTa+FTb
FTa=FTb: FTb=FibonacciTerm
next x
exit function
case n<-1
for x=-2 to n step -1
FibonacciTerm=FTa+FTc
FTa=FTc: FTc=FibonacciTerm
next x
exit function
end select
end function
</syntaxhighlight>
{{out}}
<pre>
Rosetta Code - Fibonacci sequence

n Fn
-12 -144
-11 -89
-10 -55
-9 -34
-8 -21
-7 -13
-6 -8
-5 -5
-4 -3
-3 -2
-2 -1
-1 -1
0 0
1 1
2 1
3 2
4 3
5 5
6 8
7 13
8 21
9 34
10 55
11 89
12 144

Enter a term#: 12
144
Enter a term#:
Program complete.
</pre>

==={{header|Microsoft Small Basic}}===
====Iterative====
<syntaxhighlight lang="smallbasic">' Fibonacci sequence - 31/07/2018
n = 139
f1 = 0
f2 = 1
TextWindow.WriteLine("fibo(0)="+f1)
TextWindow.WriteLine("fibo(1)="+f2)
For i = 2 To n
f3 = f1 + f2
TextWindow.WriteLine("fibo("+i+")="+f3)
f1 = f2
f2 = f3
EndFor</syntaxhighlight>
{{out}}
<pre>
fibo(139)=50095301248058391139327916261
</pre>
====Binet's Formula====
<syntaxhighlight lang="smallbasic">' Fibonacci sequence - Binet's Formula - 31/07/2018
n = 69
sq5=Math.SquareRoot(5)
phi1=(1+sq5)/2
phi2=(1-sq5)/2
phi1n=phi1
phi2n=phi2
For i = 2 To n
phi1n=phi1n*phi1
phi2n=phi2n*phi2
TextWindow.Write(Math.Floor((phi1n-phi2n)/sq5)+" ")
EndFor</syntaxhighlight>
{{out}}
<pre>
1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 12586269025 20365011074 32951280099 53316291173 86267571272 139583862445 225851433717 365435296162 591286729879 956722026041 1548008755920 2504730781961 4052739537881 6557470319842 10610209857723 17167680177565 27777890035288 44945570212853 72723460248141 117669030460994
</pre>

==={{header|Minimal BASIC}}===
{{works with|QBasic}}
{{works with|BASICA}}
{{works with|Chipmunk Basic}}
{{works with|GW-BASIC}}
{{works with|IS-BASIC}}
{{works with|MSX Basic}}
<syntaxhighlight lang="qbasic">110 REM THE ARRAY F HOLDS THE FIBONACCI NUMBERS
120 DIM F(22)
130 LET F(0) = 0
140 LET F(1) = 1
150 LET N = 1
160 REM COMPUTE THE NEXT FIBBONACCI NUMBER
170 LET F(N+1) = F(N)+F(N-1)
180 LET N = N+1
190 PRINT F(N-2);
200 REM STOP AFTER PRINTING 20 NUMBERS
210 IF N < 22 THEN 170
220 END</syntaxhighlight>

==={{header|MSX Basic}}===
{{works with|QBasic}}
{{works with|Chipmunk Basic}}
{{works with|GW-BASIC}}
<syntaxhighlight lang="qbasic">100 CLS
110 FOR N = 0 TO 15: GOSUB 130: PRINT FIBOI; : NEXT N
120 END
130 REM Iterative Fibonacci sequence
140 N1 = 0
150 N2 = 1
160 FOR K = 1 TO ABS(N)
170 SUM = N1 + N2
180 N1 = N2
190 N2 = SUM
200 NEXT K
210 IF N < 0 THEN FIBOI = N1 * ((-1) ^ ((-N) + 1)) ELSE FIBOI = N1
220 RETURN</syntaxhighlight>

==={{header|Palo Alto Tiny BASIC}}===
<syntaxhighlight lang="basic">
10 REM FIBONACCI SEQUENCE
20 INPUT "ENTER N FOR FIB(N)"N
30 LET A=0,B=1
40 FOR I=2 TO N
50 LET T=B,B=A+B,A=T
60 NEXT I
70 PRINT B
80 STOP
</syntaxhighlight>
{{out}}
2 runs.
<pre>
ENTER N FOR FIB(N):9
34
</pre>
<pre>
ENTER N FOR FIB(N):13
233
</pre>

==={{header|PowerBASIC}}===
{{trans|BASIC}}
There seems to be a limitation (dare I say, bug?) in PowerBASIC regarding how large numbers are stored. 10E17 and larger get rounded to the nearest 10. For F(n), where ABS(n) > 87, is affected like this:
actual: displayed:
F(88) 1100087778366101931 1100087778366101930
F(89) 1779979416004714189 1779979416004714190
F(90) 2880067194370816120 2880067194370816120
F(91) 4660046610375530309 4660046610375530310
F(92) 7540113804746346429 7540113804746346430

<syntaxhighlight lang="powerbasic">FUNCTION fibonacci (n AS LONG) AS QUAD
DIM u AS LONG, a AS LONG, L0 AS LONG, outP AS QUAD
STATIC fibNum() AS QUAD

u = UBOUND(fibNum)
a = ABS(n)

IF u < 1 THEN
REDIM fibNum(1)
fibNum(1) = 1
u = 1
END IF

SELECT CASE a
CASE 0 TO 92
IF a > u THEN
REDIM PRESERVE fibNum(a)
FOR L0 = u + 1 TO a
fibNum(L0) = fibNum(L0 - 1) + fibNum(L0 - 2)
IF 88 = L0 THEN fibNum(88) = fibNum(88) + 1
NEXT
END IF
IF n < 0 THEN
fibonacci = fibNum(a) * ((-1)^(a+1))
ELSE
fibonacci = fibNum(a)
END IF
CASE ELSE
'Even without the above-mentioned bug, we're still limited to
'F(+/-92), due to data type limits. (F(93) = &hA94F AD42 221F 2702)
ERROR 6
END SELECT
END FUNCTION

FUNCTION PBMAIN () AS LONG
DIM n AS LONG
#IF NOT %DEF(%PB_CC32)
OPEN "out.txt" FOR OUTPUT AS 1
#ENDIF
FOR n = -92 TO 92
#IF %DEF(%PB_CC32)
PRINT STR$(n); ": "; FORMAT$(fibonacci(n), "#")
#ELSE
PRINT #1, STR$(n) & ": " & FORMAT$(fibonacci(n), "#")
#ENDIF
NEXT
CLOSE
END FUNCTION</syntaxhighlight>

==={{header|PureBasic}}===
====Macro based calculation====
<syntaxhighlight lang="purebasic">Macro Fibonacci (n)
Int((Pow(((1+Sqr(5))/2),n)-Pow(((1-Sqr(5))/2),n))/Sqr(5))
EndMacro</syntaxhighlight>
====Recursive====
<syntaxhighlight lang="purebasic">Procedure FibonacciReq(n)
If n<2
ProcedureReturn n
Else
ProcedureReturn FibonacciReq(n-1)+FibonacciReq(n-2)
EndIf
EndProcedure</syntaxhighlight>

====Recursive & optimized with a static hash table====
This will be much faster on larger n's, this as it uses a table to store known parts instead of recalculating them.
On my machine the speedup compares to above code is
Fib(n) Speedup
20 2
25 23
30 217
40 25847
46 1156741
<syntaxhighlight lang="purebasic">Procedure Fibonacci(n)
Static NewMap Fib.i()
Protected FirstRecursion
If MapSize(Fib())= 0 ; Init the hash table the first run
Fib("0")=0: Fib("1")=1
FirstRecursion = #True
EndIf
If n >= 2
Protected.s s=Str(n)
If Not FindMapElement(Fib(),s) ; Calculate only needed parts
Fib(s)= Fibonacci(n-1)+Fibonacci(n-2)
EndIf
n = Fib(s)
EndIf
If FirstRecursion ; Free the memory when finalizing the first call
ClearMap(Fib())
EndIf
ProcedureReturn n
EndProcedure</syntaxhighlight>

'''Example'''
Fibonacci(0)= 0
Fibonacci(1)= 1
Fibonacci(2)= 1
Fibonacci(3)= 2
Fibonacci(4)= 3
Fibonacci(5)= 5
FibonacciReq(0)= 0
FibonacciReq(1)= 1
FibonacciReq(2)= 1
FibonacciReq(3)= 2
FibonacciReq(4)= 3
FibonacciReq(5)= 5

==={{header|QB64}}===
''CBTJD'': 2020/03/13
<syntaxhighlight lang="qbasic">_DEFINE F AS _UNSIGNED _INTEGER64
CLS
PRINT
PRINT "Enter 40 to more easily see the difference in calculation speeds."
PRINT
INPUT "Enter n for Fibonacci(n): ", n
PRINT
PRINT " Analytic Method (Fastest): F("; LTRIM$(STR$(n)); ") ="; fA(n)
PRINT "Iterative Method (Fast): F("; LTRIM$(STR$(n)); ") ="; fI(n)
PRINT "Recursive Method (Slow): F("; LTRIM$(STR$(n)); ") ="; fR(n)
END

' === Analytic Fibonacci Function (Fastest)
FUNCTION fA (n)
fA = INT(0.5 + (((SQR(5) + 1) / 2) ^ n) / SQR(5))
END FUNCTION

' === Iterative Fibonacci Function (Fast)
FUNCTION fI (n)
FOR i = 1 TO n
IF i < 3 THEN a = 1: b = 1
t = fI + b: fI = b: b = t
NEXT
END FUNCTION

' === Recursive Fibonacci function (Slow)
FUNCTION fR (n)
IF n <= 1 THEN
fR = n
ELSE
fR = fR(n - 1) + fR(n - 2)
END IF
END FUNCTION
</syntaxhighlight>
Fibonacci from Russia
<syntaxhighlight lang="qbasic">DIM F(80) AS DOUBLE 'FibRus.bas DANILIN
F(1) = 0: F(2) = 1
'OPEN "FibRus.txt" FOR OUTPUT AS #1
FOR i = 3 TO 80
F(i) = F(i-1)+F(i-2)
NEXT i

FOR i = 1 TO 80
f$ = STR$(F(i)): LF = 22 - LEN(f$)
n$ = ""
FOR j = 1 TO LF: n$ = " " + n$: NEXT
f$ = n$ + f$
PRINT i, f$: ' PRINT #1, i, f$
NEXT i</syntaxhighlight>
{{out}}
<pre>1 0
2 1
3 1
4 2
5 3
6 5
7 8
8 13
9 21
...
24 28657
25 46368
26 75025
...
36 9227465
37 14930352
38 24157817
...
48 2971215073
49 4807526976
50 7778742049
...
60 956722026041
61 1548008755920
62 2504730781961
...
76 2111485077978050
77 3416454622906707
78 5527939700884757
79 8944394323791464
80 1.447233402467622D+16</pre>

==={{header|QBasic}}===
{{works with|QBasic}}
{{works with|QBasic}}
{{works with|FreeBASIC}}
{{works with|FreeBASIC}}
===Iterative===
====Iterative====
<lang qbasic>FUNCTION itFib (n)
<syntaxhighlight lang="qbasic">FUNCTION itFib (n)
n1 = 0
n1 = 0
n2 = 1
n2 = 1
Line 1,199: Line 2,551:
itFib = n1
itFib = n1
END IF
END IF
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>


Next version calculates each value once, as needed, and stores the results in an array for later retreival (due to the use of <code>REDIM PRESERVE</code>, it requires [[QuickBASIC]] 4.5 or newer):
Next version calculates each value once, as needed, and stores the results in an array for later retreival (due to the use of <code>REDIM PRESERVE</code>, it requires [[QuickBASIC]] 4.5 or newer):


<lang qbasic>DECLARE FUNCTION fibonacci& (n AS INTEGER)
<syntaxhighlight lang="qbasic">DECLARE FUNCTION fibonacci& (n AS INTEGER)


REDIM SHARED fibNum(1) AS LONG
REDIM SHARED fibNum(1) AS LONG
Line 1,240: Line 2,592:
ERROR 6 'overflow
ERROR 6 'overflow
END SELECT
END SELECT
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>


{{out}} (unhandled error in final input prevents output):
{{out}} (unhandled error in final input prevents output):
Line 1,249: Line 2,601:
</pre>
</pre>


===Recursive===
====Recursive====
This example can't handle n < 0.
This example can't handle n < 0.
<syntaxhighlight lang="qbasic">FUNCTION recFib (n)

<lang qbasic>FUNCTION recFib (n)
IF (n < 2) THEN
IF (n < 2) THEN
recFib = n
recFib = n
Line 1,258: Line 2,609:
recFib = recFib(n - 1) + recFib(n - 2)
recFib = recFib(n - 1) + recFib(n - 2)
END IF
END IF
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>

===Array (Table) Lookup===


====Array (Table) Lookup====
This uses a pre-generated list, requiring much less run-time processor usage. (Since the sequence never changes, this is probably the best way to do this in "the real world". The same applies to other sequences like prime numbers, and numbers like pi and e.)
This uses a pre-generated list, requiring much less run-time processor usage. (Since the sequence never changes, this is probably the best way to do this in "the real world". The same applies to other sequences like prime numbers, and numbers like pi and e.)


<lang qbasic>DATA -1836311903,1134903170,-701408733,433494437,-267914296,165580141,-102334155
<syntaxhighlight lang="qbasic">DATA -1836311903,1134903170,-701408733,433494437,-267914296,165580141,-102334155
DATA 63245986,-39088169,24157817,-14930352,9227465,-5702887,3524578,-2178309
DATA 63245986,-39088169,24157817,-14930352,9227465,-5702887,3524578,-2178309
DATA 1346269,-832040,514229,-317811,196418,-121393,75025,-46368,28657,-17711
DATA 1346269,-832040,514229,-317811,196418,-121393,75025,-46368,28657,-17711
Line 1,284: Line 2,634:
NEXT
NEXT
PRINT
PRINT
'*****sample inputs*****</lang>
'*****sample inputs*****</syntaxhighlight>


==={{header|Commodore BASIC}}===
==={{header|Quite BASIC}}===
<syntaxhighlight lang="qbasic">100 CLS
<lang basic>10 INPUT "ENTER VALUE OF N"; N
110 rem The array F holds the Fibonacci numbers
20 N1 = 0 : N2 = 1
120 ARRAY f : rem DIM f(22) para Quite BASIC and MSX-BASIC
30 FOR K=1 TO N
40 SUM = N1+N2
130 LET f(0) = 0
50 N1 = N2
140 LET f(1) = 1
60 N2 = SUM
150 LET n = 1
160 rem Compute the NEXT Fibbonacci number
70 NEXT K
170 LET f(n+1) = f(n)+f(n-1)
80 PRINT N1</lang>
180 LET n = n+1
190 PRINT f(n-2);" ";
200 rem STOP after printing 20 numbers
210 IF n < 22 THEN GOTO 170</syntaxhighlight>


==={{header|Integer BASIC}}===
==={{header|Run BASIC}}===
<syntaxhighlight lang="runbasic">for i = 0 to 10
Only works with quite small values of <math>n</math>.
print i;" ";fibR(i);" ";fibI(i)
<lang basic> 10 INPUT N
next i
20 A=0
end
30 B=1
40 FOR I=2 TO N
function fibR(n)
50 C=B
if n < 2 then fibR = n else fibR = fibR(n-1) + fibR(n-2)
60 B=A+B
end function
70 A=C
80 NEXT I
function fibI(n)
90 PRINT B
b = 1
100 END</lang>
for i = 1 to n
t = a + b
a = b
b = t
next i
fibI = a
end function</syntaxhighlight>


==={{header|IS-BASIC}}===
==={{header|S-BASIC}}===
Note that the 23rd Fibonacci number (=28657) is the largest that can be generated without overflowing S-BASIC's integer data type.
<lang IS-BASIC>100 PROGRAM "Fibonac.bas"
<syntaxhighlight lang="basic">
110 FOR I=0 TO 20
rem - iterative function to calculate nth fibonacci number
120 PRINT "F";I,FIB(I)
function fibonacci(n = integer) = integer
130 NEXT
var f, i, p1, p2 = integer
140 DEF FIB(N)
150 NUMERIC I
p1 = 0
p2 = 1
160 LET A=0:LET B=1
170 FOR I=1 TO N
if n = 0 then
f = 0
180 LET T=A+B:LET A=B:LET B=T
else
190 NEXT
200 LET FIB=A
for i = 1 to n
f = p1 + p2
210 END DEF</lang>
p2 = p1
p1 = f
next i
end = f

rem - exercise the function
var i = integer
for i = 0 to 10
print fibonacci(i);
next i

end
</syntaxhighlight>
{{out}}
<pre> 0 1 1 2 3 5 8 13 21 34 55
</pre>


==={{header|Sinclair ZX81 BASIC}}===
==={{header|Sinclair ZX81 BASIC}}===
====Analytic====
====Analytic====
<lang basic> 10 INPUT N
<syntaxhighlight lang="basic"> 10 INPUT N
20 PRINT INT (0.5+(((SQR 5+1)/2)**N)/SQR 5)</lang>
20 PRINT INT (0.5+(((SQR 5+1)/2)**N)/SQR 5)</syntaxhighlight>


====Iterative====
====Iterative====
<lang basic> 10 INPUT N
<syntaxhighlight lang="basic"> 10 INPUT N
20 LET A=0
20 LET A=0
30 LET B=1
30 LET B=1
Line 1,337: Line 2,714:
70 LET A=C
70 LET A=C
80 NEXT I
80 NEXT I
90 PRINT B</lang>
90 PRINT B</syntaxhighlight>


====Tail recursive====
====Tail recursive====
<lang basic> 10 INPUT N
<syntaxhighlight lang="basic"> 10 INPUT N
20 LET A=0
20 LET A=0
30 LET B=1
30 LET B=1
Line 1,352: Line 2,729:
110 LET N=N-1
110 LET N=N-1
120 GOSUB 70
120 GOSUB 70
130 RETURN</lang>
130 RETURN</syntaxhighlight>

==={{header|smart BASIC}}===

The Iterative method is slow (relatively) and the Recursive method doubly so since it references the recursion function twice.

The N-th Term (fibN) function is much faster as it utilizes Binet's Formula.

<ul>
<li>fibR: Fibonacci Recursive</li>
<li>fibI: Fibonacci Iterative</li>
<li>fibN: Fibonacci N-th Term</li>
</ul>

<syntaxhighlight lang="qbasic">FOR i = 0 TO 15
PRINT fibR(i),fibI(i),fibN(i)
NEXT i

/* Recursive Method */
DEF fibR(n)
IF n <= 1 THEN
fibR = n
ELSE
fibR = fibR(n-1) + fibR(n-2)
ENDIF
END DEF

/* Iterative Method */
DEF fibI(n)
a = 0
b = 1
FOR i = 1 TO n
temp = a + b
a = b
b = temp
NEXT i
fibI = a
END DEF

/* N-th Term Method */
DEF fibN(n)
uphi = .5 + SQR(5)/2
lphi = .5 - SQR(5)/2
fibN = (uphi^n-lphi^n)/SQR(5)
END DEF</syntaxhighlight>

==={{header|Softbridge BASIC}}===
====Iterative====
<syntaxhighlight lang="basic">
Function Fibonacci(n)
x = 0
y = 1
i = 0
n = ABS(n)
If n < 2 Then
Fibonacci = n
Else
Do Until (i = n)
sum = x+y
x=y
y=sum
i=i+1
Loop
Fibonacci = x
End If

End Function
</syntaxhighlight>

==={{header|TI-83 BASIC}}===
==== Sequence table ====
<syntaxhighlight lang="ti83b">[Y=]
nMin=0
u(n)=u(n-1)+u(n-2)
u(nMin)={1,0}
[TABLE]
n u(n)
------- -------
0 0
1 1
2 1
3 2
4 3
5 5
6 8
7 13
8 21
9 34
10 55
11 89
12 144 </syntaxhighlight>

==== Iterative ====
<syntaxhighlight lang="ti83b">{0,1
While 1
Disp Ans(1
{Ans(2),sum(Ans
End</syntaxhighlight>

==== Binet's formula ====
<syntaxhighlight lang="ti83b">Prompt N
.5(1+√(5 //golden ratio
(Ans^N–(-Ans)^-N)/√(5</syntaxhighlight>

==={{header|TI-89 BASIC}}===
====Recursive====
Optimized implementation (too slow to be usable for ''n'' higher than about 12).
<syntaxhighlight lang="ti89b">fib(n)
when(n<2, n, fib(n-1) + fib(n-2))</syntaxhighlight>

====Iterative====
Unoptimized implementation (I think the for loop can be eliminated, but I'm not sure).
<syntaxhighlight lang="ti89b">fib(n)
Func
Local a,b,c,i
0→a
1→b
For i,1,n
a→c
b→a
c+b→b
EndFor
a
EndFunc</syntaxhighlight>

==={{header|Tiny BASIC}}===
{{works with|TinyBasic}}
<syntaxhighlight lang="basic">10 LET A = 0
20 LET B = 1
30 PRINT "Which F_n do you want?"
40 INPUT N
50 IF N = 0 THEN GOTO 140
60 IF N = 1 THEN GOTO 120
70 LET C = B + A
80 LET A = B
90 LET B = C
100 LET N = N - 1
110 GOTO 60
120 PRINT B
130 END
140 PRINT 0
150 END
</syntaxhighlight>

==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">FUNCTION fibonacci (n)
LET n1 = 0
LET n2 = 1
FOR k = 1 TO ABS(n)
LET sum = n1 + n2
LET n1 = n2
LET n2 = sum
NEXT k
IF n < 0 THEN
LET fibonacci = n1 * ((-1) ^ ((-n) + 1))
ELSE
LET fibonacci = n1
END IF
END FUNCTION

PRINT fibonacci(0) ! 0
PRINT fibonacci(13) ! 233
PRINT fibonacci(-42) !-267914296
PRINT fibonacci(47) ! 2971215073
END</syntaxhighlight>

==={{header|VBA}}===
Like Visual Basic .NET, but with keyword "Public" and type Variant (subtype Currency) instead of Decimal:
<syntaxhighlight lang="vb">Public Function Fib(ByVal n As Integer) As Variant
Dim fib0 As Variant, fib1 As Variant, sum As Variant
Dim i As Integer
fib0 = 0
fib1 = 1
For i = 1 To n
sum = fib0 + fib1
fib0 = fib1
fib1 = sum
Next i
Fib = fib0
End Function </syntaxhighlight>
With Currency type, maximum value is fibo(73).

The (slow) recursive version:

<syntaxhighlight lang="vba">
Public Function RFib(Term As Integer) As Long
If Term < 2 Then RFib = Term Else RFib = RFib(Term - 1) + RFib(Term - 2)
End Function
</syntaxhighlight>

With Long type, maximum value is fibo(46).

==={{header|VBScript}}===
====Non-recursive, object oriented, generator====
Defines a generator class, with a default Get property. Uses Currency for larger-than-Long values. Tests for overflow and switches to Double. Overflow information also available from class.

=====Class Definition:=====
<syntaxhighlight lang="vb">class generator
dim t1
dim t2
dim tn
dim cur_overflow
Private Sub Class_Initialize
cur_overflow = false
t1 = ccur(0)
t2 = ccur(1)
tn = ccur(t1 + t2)
end sub
public default property get generated
on error resume next

generated = ccur(tn)
if err.number <> 0 then
generated = cdbl(tn)
cur_overflow = true
end if
t1 = ccur(t2)
if err.number <> 0 then
t1 = cdbl(t2)
cur_overflow = true
end if
t2 = ccur(tn)
if err.number <> 0 then
t2 = cdbl(tn)
cur_overflow = true
end if
tn = ccur(t1+ t2)
if err.number <> 0 then
tn = cdbl(t1) + cdbl(t2)
cur_overflow = true
end if
on error goto 0
end property
public property get overflow
overflow = cur_overflow
end property
end class</syntaxhighlight>

=====Invocation:=====
<syntaxhighlight lang="vb">dim fib
set fib = new generator
dim i
for i = 1 to 100
wscript.stdout.write " " & fib
if fib.overflow then
wscript.echo
exit for
end if
next</syntaxhighlight>

{{out}}
<pre> 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 12586269025 20365011074 32951280099 53316291173 86267571272 139583862445 225851433717 365435296162 591286729879 956722026041 1548008755920 2504730781961 4052739537881 6557470319842 10610209857723 17167680177565 27777890035288 44945570212853 72723460248141 117669030460994 190392490709135 308061521170129 498454011879264 806515533049393</pre>

==={{header|Visual Basic}}===
{{works with|Visual Basic|VB6 Standard}}
Maximum integer value (7*10^28) can be obtained by using decimal type, but decimal type is only a sub type of the variant type.
<syntaxhighlight lang="vb">Sub fibonacci()
Const n = 139
Dim i As Integer
Dim f1 As Variant, f2 As Variant, f3 As Variant 'for Decimal
f1 = CDec(0): f2 = CDec(1) 'for Decimal setting
Debug.Print "fibo("; 0; ")="; f1
Debug.Print "fibo("; 1; ")="; f2
For i = 2 To n
f3 = f1 + f2
Debug.Print "fibo("; i; ")="; f3
f1 = f2
f2 = f3
Next i
End Sub 'fibonacci</syntaxhighlight>
{{Out}}
<pre>fibo( 0 )= 0
fibo( 1 )= 1
fibo( 2 )= 1
...
fibo( 137 )= 19134702400093278081449423917
fibo( 138 )= 30960598847965113057878492344
fibo( 139 )= 50095301248058391139327916261 </pre>

==={{header|Visual Basic .NET}}===
'''Platform:''' [[.NET]]
====Iterative====
{{works with|Visual Basic .NET|9.0+}}
With Decimal type, maximum value is fibo(139).
<syntaxhighlight lang="vbnet">Function Fib(ByVal n As Integer) As Decimal
Dim fib0, fib1, sum As Decimal
Dim i As Integer
fib0 = 0
fib1 = 1
For i = 1 To n
sum = fib0 + fib1
fib0 = fib1
fib1 = sum
Next
Fib = fib0
End Function</syntaxhighlight>
====Recursive====
{{works with|Visual Basic .NET|9.0+}}
<syntaxhighlight lang="vbnet">Function Seq(ByVal Term As Integer)
If Term < 2 Then Return Term
Return Seq(Term - 1) + Seq(Term - 2)
End Function</syntaxhighlight>
====BigInteger====
There is no real maximum value of BigInterger class, except the memory to store the number.
Within a minute, fibo(2000000) is a number with 417975 digits.
<syntaxhighlight lang="vbnet"> Function FiboBig(ByVal n As Integer) As BigInteger
' Fibonacci sequence with BigInteger
Dim fibn2, fibn1, fibn As BigInteger
Dim i As Integer
fibn = 0
fibn2 = 0
fibn1 = 1
If n = 0 Then
Return fibn2
ElseIf n = 1 Then
Return fibn1
ElseIf n >= 2 Then
For i = 2 To n
fibn = fibn2 + fibn1
fibn2 = fibn1
fibn1 = fibn
Next i
Return fibn
End If
Return 0
End Function 'FiboBig

Sub fibotest()
Dim i As Integer, s As String
i = 2000000 ' 2 millions
s = FiboBig(i).ToString
Console.WriteLine("fibo(" & i & ")=" & s & " - length=" & Len(s))
End Sub 'fibotest</syntaxhighlight>

====BigInteger, speedier method====
{{Libheader|System.Numerics}}
This method doesn't need to iterate the entire list, and is much faster. The 2000000 (two millionth) Fibonacci number can be found in a fraction of a second.<br/>Algorithm from [http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormula.html here, see section 3, ''Finding Fibonacci Numbers Fully''.]
<syntaxhighlight lang="vbnet">Imports System
Imports System.Collections.Generic
Imports BI = System.Numerics.BigInteger

Module Module1

' A sparse array of values calculated along the way
Dim sl As SortedList(Of Integer, BI) = New SortedList(Of Integer, BI)()

' Square a BigInteger
Function sqr(ByVal n As BI) As BI
Return n * n
End Function

' Helper routine for Fsl(). It adds an entry to the sorted list when necessary
Sub IfNec(n As Integer)
If Not sl.ContainsKey(n) Then sl.Add(n, Fsl(n))
End Sub

' This routine is semi-recursive, but doesn't need to evaluate every number up to n.
' Algorithm from here: http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormula.html#section3
Function Fsl(ByVal n As Integer) As BI
If n < 2 Then Return n
Dim n2 As Integer = n >> 1, pm As Integer = n2 + ((n And 1) << 1) - 1 : IfNec(n2) : IfNec(pm)
Return If(n2 > pm, (2 * sl(pm) + sl(n2)) * sl(n2), sqr(sl(n2)) + sqr(sl(pm)))
End Function

' Conventional iteration method (not used here)
Function Fm(ByVal n As BI) As BI
If n < 2 Then Return n
Dim cur As BI = 0, pre As BI = 1
For i As Integer = 0 To n - 1
Dim sum As BI = cur + pre : pre = cur : cur = sum : Next : Return cur
End Function

Sub Main()
Dim vlen As Integer, num As Integer = 2_000_000, digs As Integer = 35
Dim sw As System.Diagnostics.Stopwatch = System.Diagnostics.Stopwatch.StartNew()
Dim v As BI = Fsl(num) : sw.[Stop]()
Console.Write("{0:n3} ms to calculate the {1:n0}th Fibonacci number, ", sw.Elapsed.TotalMilliseconds, num)
vlen = CInt(Math.Ceiling(BI.Log10(v))) : Console.WriteLine("number of digits is {0}", vlen)
If vlen < 10000 Then
sw.Restart() : Console.WriteLine(v) : sw.[Stop]()
Console.WriteLine("{0:n3} ms to write it to the console.", sw.Elapsed.TotalMilliseconds)
Else
Console.Write("partial: {0}...{1}", v / BI.Pow(10, vlen - digs), v Mod BI.Pow(10, digs))
End If
End Sub
End Module</syntaxhighlight>
{{out}}
<pre>120.374 ms to calculate the 2,000,000th Fibonacci number, number of digits is 417975
partial: 85312949175076415430516606545038251...91799493108960825129188777803453125</pre>

==={{header|Xojo}}===
Pass n to this function where n is the desired number of iterations. This example uses the UInt64 datatype which is as unsigned 64 bit integer. As such, it overflows after the 93rd iteration.
<syntaxhighlight lang="vb">Function fibo(n As Integer) As UInt64

Dim noOne As UInt64 = 1
Dim noTwo As UInt64 = 1
Dim sum As UInt64

For i As Integer = 3 To n
sum = noOne + noTwo
noTwo = noOne
noOne = sum
Next

Return noOne
End Function</syntaxhighlight>

==={{header|Yabasic}}===
====Iterative====
<syntaxhighlight lang="vbnet">sub fibonacciI (n)
local n1, n2, k, sum

n1 = 0
n2 = 1
for k = 1 to abs(n)
sum = n1 + n2
n1 = n2
n2 = sum
next k
if n < 1 then
return n1 * ((-1) ^ ((-n) + 1))
else
return n1
end if
end sub</syntaxhighlight>

====Recursive====
Only positive numbers
<syntaxhighlight lang="vbnet">sub fibonacciR(n)
if n <= 1 then
return n
else
return fibonacciR(n-1) + fibonacciR(n-2)
end if
end sub</syntaxhighlight>

====Analytic====
Only positive numbers
<syntaxhighlight lang="vbnet">sub fibonacciA (n)
return int(0.5 + (((sqrt(5) + 1) / 2) ^ n) / sqrt(5))
end sub</syntaxhighlight>

====Binet's formula====
Fibonacci sequence using the Binet formula
<syntaxhighlight lang="vbnet">sub fibonacciB(n)
local sq5, phi1, phi2, dn1, dn2, k

sq5 = sqrt(5)
phi1 = (1 + sq5) / 2
phi2 = (1 - sq5) / 2
dn1 = phi1: dn2 = phi2
for k = 0 to n
dn1 = dn1 * phi1
dn2 = dn2 * phi2
print int(((dn1 - dn2) / sq5) + .5);
next k
end sub</syntaxhighlight>

==={{header|ZX Spectrum Basic}}===
====Iterative====
<syntaxhighlight lang="zxbasic">10 REM Only positive numbers
20 LET n=10
30 LET n1=0: LET n2=1
40 FOR k=1 TO n
50 LET sum=n1+n2
60 LET n1=n2
70 LET n2=sum
80 NEXT k
90 PRINT n1</syntaxhighlight>

====Analytic====
<syntaxhighlight lang="zxbasic">10 DEF FN f(x)=INT (0.5+(((SQR 5+1)/2)^x)/SQR 5)</syntaxhighlight>


=={{header|Batch File}}==
=={{header|Batch File}}==
Recursive version
Recursive version
<lang dos>::fibo.cmd
<syntaxhighlight lang="dos">::fibo.cmd
@echo off
@echo off
if "%1" equ "" goto :eof
if "%1" equ "" goto :eof
Line 1,376: Line 3,228:
set r2=%errorlevel%
set r2=%errorlevel%
set /a r0 = r1 + r2
set /a r0 = r1 + r2
exit /b !r0!</lang>
exit /b !r0!</syntaxhighlight>


{{out}}
{{out}}
Line 1,393: Line 3,245:
>fibo.cmd 16
>fibo.cmd 16
987</pre>
987</pre>



=={{header|Battlestar}}==
=={{header|Battlestar}}==


<!--- works with C syntax highlighting --->
<!--- works with C syntax highlighting --->
<syntaxhighlight lang="c">
<lang c>
// Fibonacci sequence, recursive version
// Fibonacci sequence, recursive version
fun fibb
fun fibb
Line 1,442: Line 3,293:


// vim: set syntax=c ts=4 sw=4 et:
// vim: set syntax=c ts=4 sw=4 et:
</syntaxhighlight>
</lang>

=={{header|BBC BASIC}}==
<lang bbcbasic> PRINT FNfibonacci_r(1), FNfibonacci_i(1)
PRINT FNfibonacci_r(13), FNfibonacci_i(13)
PRINT FNfibonacci_r(26), FNfibonacci_i(26)
END
DEF FNfibonacci_r(N)
IF N < 2 THEN = N
= FNfibonacci_r(N-1) + FNfibonacci_r(N-2)
DEF FNfibonacci_i(N)
LOCAL F, I, P, T
IF N < 2 THEN = N
P = 1
FOR I = 1 TO N
T = F
F += P
P = T
NEXT
= F
</lang>
{{out}}
<pre> 1 1
233 233
121393 121393</pre>


=={{header|bc}}==
=={{header|bc}}==
=== iterative ===
=== iterative ===
<lang bc>#! /usr/bin/bc -q
<syntaxhighlight lang="bc">#! /usr/bin/bc -q


define fib(x) {
define fib(x) {
Line 1,486: Line 3,311:
}
}
fib(1000)
fib(1000)
quit</lang>
quit</syntaxhighlight>


=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"

let fib(n) = n<=1 -> n, valof
$( let a=0 and b=1
for i=2 to n
$( let c=a
a := b
b := a+c
$)
resultis b
$)

let start() be
for i=0 to 10 do
writef("F_%N*T= %N*N", i, fib(i))</syntaxhighlight>
{{out}}
<pre>F_0 = 0
F_1 = 1
F_2 = 1
F_3 = 2
F_4 = 3
F_5 = 5
F_6 = 8
F_7 = 13
F_8 = 21
F_9 = 34
F_10 = 55</pre>


=={{header|beeswax}}==
=={{header|beeswax}}==


<lang beeswax> #>'#{;
<syntaxhighlight lang="beeswax"> #>'#{;
_`Enter n: `TN`Fib(`{`)=`X~P~K#{;
_`Enter n: `TN`Fib(`{`)=`X~P~K#{;
#>~P~L#MM@>+@'q@{;
#>~P~L#MM@>+@'q@{;
b~@M<</lang>
b~@M<</syntaxhighlight>


Example output:
Example output:
Line 1,500: Line 3,353:
Notice the UInt64 wrap-around at <code>Fib(94)</code>!
Notice the UInt64 wrap-around at <code>Fib(94)</code>!


<lang julia>julia> beeswax("n-th Fibonacci number.bswx")
<syntaxhighlight lang="julia">julia> beeswax("n-th Fibonacci number.bswx")
Enter n: i0
Enter n: i0


Line 1,528: Line 3,381:
Fib(94)=1293530146158671551
Fib(94)=1293530146158671551
Program finished!</lang>
Program finished!</syntaxhighlight>


=={{header|Befunge}}==
=={{header|Befunge}}==
<lang befunge>00:.1:.>:"@"8**++\1+:67+`#@_v
<syntaxhighlight lang="befunge">00:.1:.>:"@"8**++\1+:67+`#@_v
^ .:\/*8"@"\%*8"@":\ <</lang>
^ .:\/*8"@"\%*8"@":\ <</syntaxhighlight>

=={{header|BlitzMax}}==
<syntaxhighlight lang="blitzmax">local a:int = 0, b:int = 1, c:int = 1, n:int

n = int(input( "Enter n: "))
if n = 0 then
print 0
end
else if n = 1
print 1
end
end if

while n>2
a = b
b = c
c = a + b
n = n - 1
wend
print c</syntaxhighlight>

=={{header|Blue}}==
<syntaxhighlight lang="blue">
: fib ( nth:ecx -- result:edi ) 1 0
: compute ( times:ecx accum:eax scratch:edi -- result:edi ) xadd latest loop ;

: example ( -- ) 11 fib drop ;
</syntaxhighlight>

=={{header|BQN}}==

All given functions return the nth element in the sequence.
=== Recursive ===
A primitive recursive can be done with predicates:
<syntaxhighlight lang="bqn">Fib ← {𝕩>1 ? (𝕊 𝕩-1) + 𝕊 𝕩-2; 𝕩}</syntaxhighlight>
Or, it can be done with the Choose(<code>◶</code>) modifier:
<syntaxhighlight lang="bqn">Fib2 ← {(𝕩-1) (𝕩>1)◶⟨𝕩, +○𝕊⟩ 𝕩-2}</syntaxhighlight>

=== Iterative ===
An iterative solution can be made with the Repeat(<code>⍟</code>) modifier:
<syntaxhighlight lang="bqn">{⊑(+`⌽)⍟𝕩 0‿1}</syntaxhighlight>

=={{header|Bracmat}}==
===Recursive===
<syntaxhighlight lang="bracmat">fib=.!arg:<2|fib$(!arg+-2)+fib$(!arg+-1)</syntaxhighlight>

fib$30
832040

===Iterative===
<syntaxhighlight lang="bracmat">(fib=
last i this new
. !arg:<2
| 0:?last:?i
& 1:?this
& whl
' ( !i+1:<!arg:?i
& !last+!this:?new
& !this:?last
& !new:?this
)
& !this
)</syntaxhighlight>

fib$777
1081213530912648191985419587942084110095342850438593857649766278346130479286685742885693301250359913460718567974798268702550329302771992851392180275594318434818082


=={{header|Brainf***}}==
=={{header|Brainf***}}==
{{works with|Brainf***|implementations with unbounded cell size}}
{{works with|Brainf***|implementations with unbounded cell size}}
The first cell contains ''n'' (10), the second cell will contain ''fib(n)'' (55), and the third cell will contain ''fib(n-1)'' (34).
The first cell contains ''n'' (10), the second cell will contain ''fib(n)'' (55), and the third cell will contain ''fib(n-1)'' (34).
<lang bf>++++++++++
<syntaxhighlight lang="bf">++++++++++
>>+<<[->[->+>+<<]>[-<+>]>[-<+>]<<<]</lang>
>>+<<[->[->+>+<<]>[-<+>]>[-<+>]<<<]</syntaxhighlight>


The following generates n fibonacci numbers and prints them, though not in ascii.
The following generates n fibonacci numbers and prints them, though not in ascii.
It does have a limit due to the cells usually being 1 byte in size.
It does have a limit due to the cells usually being 1 byte in size.
<lang bf>+++++ +++++ #0 set to n
<syntaxhighlight lang="bf">+++++ +++++ #0 set to n
>> + Init #2 to 1
>> + Init #2 to 1
<<
<<
Line 1,578: Line 3,497:
]
]
<<<< Back to #0
<<<< Back to #0
]</lang>
]</syntaxhighlight>

=={{header|Bracmat}}==
===Recursive===
<lang bracmat>fib=.!arg:<2|fib$(!arg+-2)+fib$(!arg+-1)</lang>

fib$30
832040

===Iterative===
<lang bracmat>(fib=
last i this new
. !arg:<2
| 0:?last:?i
& 1:?this
& whl
' ( !i+1:<!arg:?i
& !last+!this:?new
& !this:?last
& !new:?this
)
& !this
)</lang>

fib$777
1081213530912648191985419587942084110095342850438593857649766278346130479286685742885693301250359913460718567974798268702550329302771992851392180275594318434818082


=={{header|Brat}}==
=={{header|Brat}}==
===Recursive===
===Recursive===
<lang brat>fibonacci = { x |
<syntaxhighlight lang="brat">fibonacci = { x |
true? x < 2, x, { fibonacci(x - 1) + fibonacci(x - 2) }
true? x < 2, x, { fibonacci(x - 1) + fibonacci(x - 2) }
}</lang>
}</syntaxhighlight>


===Tail Recursive===
===Tail Recursive===
<lang brat>fib_aux = { x, next, result |
<syntaxhighlight lang="brat">fib_aux = { x, next, result |
true? x == 0,
true? x == 0,
result,
result,
Line 1,620: Line 3,514:
fibonacci = { x |
fibonacci = { x |
fib_aux x, 1, 0
fib_aux x, 1, 0
}</lang>
}</syntaxhighlight>


===Memoization===
===Memoization===
<lang brat>cache = hash.new
<syntaxhighlight lang="brat">cache = hash.new


fibonacci = { x |
fibonacci = { x |
Line 1,629: Line 3,523:
{ cache[x] }
{ cache[x] }
{true? x < 2, x, { cache[x] = fibonacci(x - 1) + fibonacci(x - 2) }}
{true? x < 2, x, { cache[x] = fibonacci(x - 1) + fibonacci(x - 2) }}
}</lang>
}</syntaxhighlight>

=={{header|Bruijn}}==

<syntaxhighlight lang="bruijn">
:import std/Combinator .
:import std/Math .
:import std/List .

# unary/Church fibonacci (moderately fast but very high space complexity)
fib-unary [0 [[[2 0 [2 (1 0)]]]] k i]

:test (fib-unary (+6u)) ((+8u))

# ternary fibonacci using infinite list iteration (very fast)
fib-list \index fibs
fibs head <$> (iterate &[[0 : (1 + 0)]] ((+0) : (+1)))

:test (fib-list (+6)) ((+8))

# recursive fib (very slow)
fib-rec y [[0 <? (+1) (+0) (0 <? (+2) (+1) rec)]]
rec (1 --0) + (1 --(--0))

:test (fib-rec (+6)) ((+8))
</syntaxhighlight>

Performance using <code>HigherOrder</code> reduction without optimizations:
<syntaxhighlight>
> :time fib-list (+1000)
0.9 seconds
> :time fib-unary (+50u)
1.7 seconds
> :time fib-rec (+25)
5.1 seconds
> :time fib-list (+50)
0.0006 seconds
</syntaxhighlight>


=={{header|Burlesque}}==
=={{header|Burlesque}}==


<lang burlesque>
<syntaxhighlight lang="burlesque">
{0 1}{^^++[+[-^^-]\/}30.*\[e!vv
{0 1}{^^++[+[-^^-]\/}30.*\[e!vv
</syntaxhighlight>
</lang>


<lang burlesque>
<syntaxhighlight lang="burlesque">
0 1{{.+}c!}{1000.<}w!
0 1{{.+}c!}{1000.<}w!
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
===Recursive===
===Recursive===
<lang c>long long fibb(long long a, long long b, int n) {
<syntaxhighlight lang="c">long long fibb(long long a, long long b, int n) {
return (--n>0)?(fibb(b, a+b, n)):(a);
return (--n>0)?(fibb(b, a+b, n)):(a);
}</lang>
}</syntaxhighlight>


===Iterative===
===Iterative===
<lang c>long long int fibb(int n) {
<syntaxhighlight lang="c">long long int fibb(int n) {
int fnow = 0, fnext = 1, tempf;
int fnow = 0, fnext = 1, tempf;
while(--n>0){
while(--n>0){
Line 1,656: Line 3,587:
}
}
return fnext;
return fnext;
}</lang>
}</syntaxhighlight>


===Analytic===
===Analytic===
<lang c>#include <tgmath.h>
<syntaxhighlight lang="c">#include <tgmath.h>
#define PHI ((1 + sqrt(5))/2)
#define PHI ((1 + sqrt(5))/2)


long long unsigned fib(unsigned n) {
long long unsigned fib(unsigned n) {
return floor( (pow(PHI, n) - pow(1 - PHI, n))/sqrt(5) );
return floor( (pow(PHI, n) - pow(1 - PHI, n))/sqrt(5) );
}</lang>
}</syntaxhighlight>


===Generative===
===Generative===
{{trans|Python}}
{{trans|Python}}
{{works with|gcc|version 4.1.2 20080704 (Red Hat 4.1.2-44)}}
{{works with|gcc|version 4.1.2 20080704 (Red Hat 4.1.2-44)}}
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
typedef enum{false=0, true=!0} bool;
typedef enum{false=0, true=!0} bool;
typedef void iterator;
typedef void iterator;
Line 1,705: Line 3,636:
OD;
OD;
printf("...\n");
printf("...\n");
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,712: Line 3,643:


===Fast method for a single large value===
===Fast method for a single large value===
<lang c>#include <stdlib.h>
<syntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>
#include <gmp.h>
#include <gmp.h>
Line 1,785: Line 3,716:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,798: Line 3,729:
1919488
1919488
</pre>
</pre>

=={{header|C sharp|C#}}==

=== Recursive ===
<syntaxhighlight lang="csharp">
public static ulong Fib(uint n) {
return (n < 2)? n : Fib(n - 1) + Fib(n - 2);
}
</syntaxhighlight>

=== Tail-Recursive ===
<syntaxhighlight lang="csharp">
public static ulong Fib(uint n) {
return Fib(0, 1, n);
}

private static ulong Fib(ulong a, ulong b, uint n) {
return (n < 1)? a :(n == 1)? b : Fib(b, a + b, n - 1);
}
</syntaxhighlight>

=== Iterative ===
<syntaxhighlight lang="csharp">
public static ulong Fib(uint x) {
if (x == 0) return 0;

ulong prev = 0;
ulong next = 1;
for (int i = 1; i < x; i++)
{
ulong sum = prev + next;
prev = next;
next = sum;
}
return next;
}
</syntaxhighlight>

=== Iterative ===
<syntaxhighlight lang="csharp">
using System; using System.Text; // FIBRUS.cs Russia
namespace Fibrus { class Program { static void Main()
{ long fi1=1; long fi2=1; long fi3=1; int da; int i; int d;
for (da=1; da<=78; da++) // rextester.com/MNGUV70257
{ d = 20-Convert.ToInt32((Convert.ToString(fi3)).Length);
for (i=1; i<d; i++) Console.Write(".");
Console.Write(fi3); Console.Write(" "); Console.WriteLine(da);
fi3 = fi2 + fi1;
fi1 = fi2;
fi2 = fi3;
}}}}
</syntaxhighlight>
{{out}}
<pre>
..................1 1
..................2 2
..................3 3
...
...5527939700884757 76
...8944394323791464 77
..14472334024676221 78
</pre>

=== Eager-Generative ===
<syntaxhighlight lang="csharp">
public static IEnumerable<long> Fibs(uint x) {
IList<ulong> fibs = new List<ulong>();

ulong prev = -1;
ulong next = 1;
for (int i = 0; i < x; i++)
{
long sum = prev + next;
prev = next;
next = sum;
fibs.Add(sum);
}
return fibs;
}
</syntaxhighlight>

=== Lazy-Generative ===
<syntaxhighlight lang="csharp">
public static IEnumerable<ulong> Fibs(uint x) {
ulong prev = -1;
ulong next = 1;
for (uint i = 0; i < x; i++) {
ulong sum = prev + next;
prev = next;
next = sum;
yield return sum;
}
}
</syntaxhighlight>

=== Analytic ===
This returns digits up to the 93<sup>rd</sup> Fibonacci number, but the digits become inaccurate past the 71<sup>st</sup>. There is custom rounding applied to the result that allows the function to be accurate at the 71<sup>st</sup> number instead of topping out at the 70<sup>th</sup>.
<syntaxhighlight lang="csharp">static double r5 = Math.Sqrt(5.0), Phi = (r5 + 1.0) / 2.0;

static ulong fib(uint n) {
if (n > 71) throw new ArgumentOutOfRangeException("n", n, "Needs to be smaller than 72.");
double r = Math.Pow(Phi, n) / r5;
return (ulong)(n < 64 ? Math.Round(r) : Math.Floor(r)); }</syntaxhighlight>To get to the 93<sup>rd</sup> Fibonacci number, one must use the decimal type, rather than the double type, like this:<syntaxhighlight lang="csharp">static decimal Sqrt_dec(decimal x, decimal g) { decimal t, lg;
do { t = x / g; lg = g; g = (t + g) / 2M; } while (lg != g);
return g; }

static decimal Pow_dec (decimal bas, uint exp) {
if (exp == 0) return 1M;
decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp;
if ((exp & 1) == 1) tmp *= bas; return tmp; }

static decimal r5 = Sqrt_dec(5.0M, (decimal)Math.Sqrt(5.0)),
Phi = (r5 + 1.0M) / 2.0M;

static ulong fib(uint n) {
if (n > 93) throw new ArgumentOutOfRangeException("n", n, "Needs to be smaller than 94.");
decimal r = Pow_dec(Phi, n) / r5;
return (ulong)(n < 64 ? Math.Round(r) : Math.Floor(r)); }</syntaxhighlight>Note that the Math.Pow() function and the Math.Sqrt() function must be replaced with ones returning the decimal type.<br/><br/>If one allows the fib() function to return the decimal type, one can reach the 138<sup>th</sup> Fibonacci number. However, the accuracy is lost after the 128<sup>th.</sup><syntaxhighlight lang="csharp">static decimal Sqrt_dec(decimal x, decimal g) { decimal t, lg;
do { t = x / g; lg = g; g = (t + g) / 2M; } while (lg != g);
return g; }

static decimal Pow_dec (decimal bas, uint exp) {
if (exp == 0) return 1M;
decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp;
if ((exp & 1) == 1) tmp *= bas; return tmp; }

static decimal r5 = Sqrt_dec(5.0M, (decimal)Math.Sqrt(5.0)),
Phi = (r5 + 1.0M) / 2.0M;

static decimal fib(uint n) {
if (n > 128) throw new ArgumentOutOfRangeException("n", n, "Needs to be smaller than 129.");
decimal r = Pow_dec(Phi, n) / r5;
return n < 64 ? Math.Round(r) : Math.Floor(r); }</syntaxhighlight>

=== Matrix ===
Algorithm is based on
:<math>\begin{pmatrix}1&1\\1&0\end{pmatrix}^n = \begin{pmatrix}F(n+1)&F(n)\\F(n)&F(n-1)\end{pmatrix}</math>.

Needs <code>System.Windows.Media.Matrix</code> or similar Matrix class.
Calculates in <math>O(n)</math>.
<syntaxhighlight lang="csharp">
public static ulong Fib(uint n) {
var M = new Matrix(1,0,0,1);
var N = new Matrix(1,1,1,0);
for (uint i = 1; i < n; i++) M *= N;
return (ulong)M[0][0];
}
</syntaxhighlight>
Needs <code>System.Windows.Media.Matrix</code> or similar Matrix class.
Calculates in <math>O(\log{n})</math>.
<syntaxhighlight lang="csharp">
private static Matrix M;
private static readonly Matrix N = new Matrix(1,1,1,0);

public static ulong Fib(uint n) {
M = new Matrix(1,0,0,1);
MatrixPow(n-1);
return (ulong)M[0][0];
}

private static void MatrixPow(double n){
if (n > 1) {
MatrixPow(n/2);
M *= M;
}
if (n % 2 == 0) M *= N;
}
</syntaxhighlight>

=== Array (Table) Lookup ===
<syntaxhighlight lang="csharp">
private static int[] fibs = new int[]{ -1836311903, 1134903170,
-701408733, 433494437, -267914296, 165580141, -102334155,
63245986, -39088169, 24157817, -14930352, 9227465, -5702887,
3524578, -2178309, 1346269, -832040, 514229, -317811, 196418,
-121393, 75025, -46368, 28657, -17711, 10946, -6765, 4181,
-2584, 1597, -987, 610, -377, 233, -144, 89, -55, 34, -21, 13,
-8, 5, -3, 2, -1, 1, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711,
28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040,
1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817,
39088169, 63245986, 102334155, 165580141, 267914296, 433494437,
701408733, 1134903170, 1836311903};

public static int Fib(int n) {
if(n < -46 || n > 46) throw new ArgumentOutOfRangeException("n", n, "Has to be between -46 and 47.")
return fibs[n+46];
}
</syntaxhighlight>
===Arbitrary Precision===
{{libheader|System.Numerics}}
This large step recurrence routine can calculate the two millionth Fibonacci number in under 1 / 5 second at tio.run. This routine can generate the fifty millionth Fibonacci number in under 30 seconds at tio.run. The unused conventional iterative method times out at two million on tio.run, you can only go to around 1,290,000 or so to keep the calculation time (plus string conversion time) under the 60 second timeout limit there. When using this large step recurrence method, it takes around 5 seconds to convert the two millionth Fibonacci number (417975 digits) into a string (so that one may count those digits).

<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
class Program
{
// A sparse array of values calculated along the way
static SortedList<int, BI> sl = new SortedList<int, BI>();
// This routine is semi-recursive, but doesn't need to evaluate every number up to n.
// Algorithm from here: http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormula.html#section3
static BI Fsl(int n)
{
if (n < 2) return n;
int n2 = n >> 1, pm = n2 + ((n & 1) << 1) - 1; IfNec(n2); IfNec(pm);
return n2 > pm ? (2 * sl[pm] + sl[n2]) * sl[n2] : sqr(sl[n2]) + sqr(sl[pm]);
// Helper routine for Fsl(). It adds an entry to the sorted list when necessary
void IfNec(int x) { if (!sl.ContainsKey(x)) sl.Add(x, Fsl(x)); }
// Helper function to square a BigInteger
BI sqr(BI x) { return x * x; }
}
// Conventional iteration method (not used here)
public static BI Fm(BI n)
{
if (n < 2) return n; BI cur = 0, pre = 1;
for (int i = 0; i <= n - 1; i++) { BI sum = cur + pre; pre = cur; cur = sum; }
return cur;
}
public static void Main()
{
int num = 2_000_000, digs = 35, vlen;
var sw = System.Diagnostics.Stopwatch.StartNew(); var v = Fsl(num); sw.Stop();
Console.Write("{0:n3} ms to calculate the {1:n0}th Fibonacci number, ",
sw.Elapsed.TotalMilliseconds, num);
Console.WriteLine("number of digits is {0}", vlen = (int)Math.Ceiling(BI.Log10(v)));
if (vlen < 10000) {
sw.Restart(); Console.WriteLine(v); sw.Stop();
Console.WriteLine("{0:n3} ms to write it to the console.", sw.Elapsed.TotalMilliseconds);
} else
Console.Write("partial: {0}...{1}", v / BI.Pow(10, vlen - digs), v % BI.Pow(10, digs));
}
}</syntaxhighlight>
{{out}}
<pre>137.209 ms to calculate the 2,000,000th Fibonacci number, number of digits is 417975
partial: 85312949175076415430516606545038251...91799493108960825129188777803453125
</pre>

===Shift PowerMod===
{{libheader|System.Numerics}}
Illustrated here is an algorithm to compute a Fibonacci number directly, without needing to calculate any of the Fibonacci numbers less than the desired result. It uses shifting and the power mod function (<code>BigInteger.ModPow()</code> in C#). It calculates more quickly than the large step recurrence routine (illustrated above) for smaller Fibonacci numbers (less than 2800 digits or so, around Fibonacci(13000)), but gets slower for larger ones, as the intermediate BigIntegers created are very large, much larger than the Fibonacci result.

Also included is a routine that returns an array of Fibonacci numbers (<code>fibTab()</code>). It reuses the intermediate large shifted BigIntegers on suceeding iterations, therfore it is a little more efficient than calling the oneshot (<code>oneFib()</code>) routine repeatedly from a loop.

<syntaxhighlight lang="csharp">using System;
using BI = System.Numerics.BigInteger;

class Program {
// returns the nth Fibonacci number without calculating 0..n-1
static BI oneFib(int n) {
BI z = (BI)1 << ++n;
return BI.ModPow(z, n, (z << n) - z - 1) % z;
}

// returns an array of Fibonacci numbers from the 0th to the nth
static BI[] fibTab(int n) {
var res = new BI[++n];
BI z = (BI)1 << 1, zz = z << 1;
for (int i = 0; i < n; ) {
res[i] = BI.ModPow(z, ++i, zz - z - 1) % z;
z <<= 1; zz <<= 2;
}
return res;
}
static void Main(string[] args) {
int n = 20;
Console.WriteLine("Fibonacci numbers 0..{0}: {1}", n, string.Join(" ",fibTab(n)));
n = 1000;
Console.WriteLine("Fibonacci({0}): {1}", n, oneFib(n));
}
}</syntaxhighlight>
{{out}}
<pre>Fibonacci numbers 0..20: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
Fibonacci(1000): 43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875</pre>


=={{header|C++}}==
=={{header|C++}}==
Using unsigned int, this version only works up to 48 before fib overflows.
Using unsigned int, this version only works up to 48 before fib overflows.
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>


int main()
int main()
Line 1,816: Line 4,027:


return 0;
return 0;
}</lang>
}</syntaxhighlight>




Line 1,822: Line 4,033:
This version does not have an upper bound.
This version does not have an upper bound.


<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <gmpxx.h>
#include <gmpxx.h>


Line 1,842: Line 4,053:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>


Version using transform:
Version using transform:
<lang cpp>#include <algorithm>
<syntaxhighlight lang="cpp">#include <algorithm>
#include <vector>
#include <vector>
#include <functional>
#include <functional>
Line 1,857: Line 4,068:
// "v" now contains the Fibonacci sequence from 0 up
// "v" now contains the Fibonacci sequence from 0 up
return v[n];
return v[n];
}</lang>
}</syntaxhighlight>


Far-fetched version using adjacent_difference:
Far-fetched version using adjacent_difference:
<lang cpp>#include <numeric>
<syntaxhighlight lang="cpp">#include <numeric>
#include <vector>
#include <vector>
#include <functional>
#include <functional>
Line 1,872: Line 4,083:
return v[n-1];
return v[n-1];
}
}
</syntaxhighlight>
</lang>


Version which computes at compile time with metaprogramming:
Version which computes at compile time with metaprogramming:
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>


template <int n> struct fibo
template <int n> struct fibo
Line 1,898: Line 4,109:
std::cout<<fibo<46>::value<<std::endl;
std::cout<<fibo<46>::value<<std::endl;
return 0;
return 0;
}</lang>
}</syntaxhighlight>


The following version is based on fast exponentiation:
The following version is based on fast exponentiation:
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>


inline void fibmul(int* f, int* g)
inline void fibmul(int* f, int* g)
Line 1,935: Line 4,146:
std::cout << fibonacci(i) << " ";
std::cout << fibonacci(i) << " ";
std::cout << std::endl;
std::cout << std::endl;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
===Using Zeckendorf Numbers===
===Using Zeckendorf Numbers===
The nth fibonacci is represented as Zeckendorf 1 followed by n-1 zeroes. [[Zeckendorf number representation#Using a C++11 User Defined Literal|Here]] I define a class N which defines the operations increment ++() and comparison <=(other N) for Zeckendorf Numbers.
The nth fibonacci is represented as Zeckendorf 1 followed by n-1 zeroes. [[Zeckendorf number representation#Using a C++11 User Defined Literal|Here]] I define a class N which defines the operations increment ++() and comparison <=(other N) for Zeckendorf Numbers.
<lang cpp>
<syntaxhighlight lang="cpp">
// Use Zeckendorf numbers to display Fibonacci sequence.
// Use Zeckendorf numbers to display Fibonacci sequence.
// Nigel Galloway October 23rd., 2012
// Nigel Galloway October 23rd., 2012
Line 1,956: Line 4,167:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,964: Line 4,175:
===Using Standard Template Library===
===Using Standard Template Library===
Possibly less "Far-fetched version".
Possibly less "Far-fetched version".
<lang cpp>
<syntaxhighlight lang="cpp">
// Use Standard Template Library to display Fibonacci sequence.
// Use Standard Template Library to display Fibonacci sequence.
// Nigel Galloway March 30th., 2013
// Nigel Galloway March 30th., 2013
Line 1,976: Line 4,187:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946

=={{header|C sharp|C#}}==

=== Recursive ===
<lang csharp>
public static ulong Fib(uint n) {
return (n < 2)? n : Fib(n - 1) + Fib(n - 2);
}
</lang>

=== Tail-Recursive ===
<lang csharp>
public static ulong Fib(uint n) {
return Fib(0, 1, n);
}

private static ulong Fib(ulong a, ulong b, uint n) {
return (n < 1)? a :(n == 1)? b : Fib(b, a + b, n - 1);
}
</lang>

=== Iterative ===
<lang csharp>
public static ulong Fib(uint x) {
if (x == 0) return 0;

ulong prev = 0;
ulong next = 1;
for (int i = 1; i < x; i++)
{
ulong sum = prev + next;
prev = next;
next = sum;
}
return next;
}
</lang>

=== Eager-Generative ===
<lang csharp>
public static IEnumerable<long> Fibs(uint x) {
IList<ulong> fibs = new List<ulong>();

ulong prev = -1;
ulong next = 1;
for (int i = 0; i < x; i++)
{
long sum = prev + next;
prev = next;
next = sum;
fibs.Add(sum);
}
return fibs;
}
</lang>

=== Lazy-Generative ===
<lang csharp>
public static IEnumerable<ulong> Fibs(uint x) {
ulong prev = -1;
ulong next = 1;
for (uint i = 0; i < x; i++) {
ulong sum = prev + next;
prev = next;
next = sum;
yield return sum;
}
}
</lang>

=== Analytic ===
Only works to the 92<sup>th</sup> fibonacci number.
<lang csharp>
private static double Phi = ((1d + Math.Sqrt(5d))/2d);
private static double D = 1d/Math.Sqrt(5d);

ulong Fib(uint n) {
if(n > 92) throw new ArgumentOutOfRangeException("n", n, "Needs to be smaller than 93.");
return (ulong)((Phi^n) - (1d - Phi)^n))*D);
}
</lang>

=== Matrix ===
Algorithm is based on
:<math>\begin{pmatrix}1&1\\1&0\end{pmatrix}^n = \begin{pmatrix}F(n+1)&F(n)\\F(n)&F(n-1)\end{pmatrix}</math>.

Needs <code>System.Windows.Media.Matrix</code> or similar Matrix class.
Calculates in <math>O(n)</math>.
<lang csharp>
public static ulong Fib(uint n) {
var M = new Matrix(1,0,0,1);
var N = new Matrix(1,1,1,0);
for (uint i = 1; i < n; i++) M *= N;
return (ulong)M[0][0];
}
</lang>
Needs <code>System.Windows.Media.Matrix</code> or similar Matrix class.
Calculates in <math>O(\log{n})</math>.
<lang csharp>
private static Matrix M;
private static readonly Matrix N = new Matrix(1,1,1,0);

public static ulong Fib(uint n) {
M = new Matrix(1,0,0,1);
MatrixPow(n-1);
return (ulong)M[0][0];
}

private static void MatrixPow(double n){
if (n > 1) {
MatrixPow(n/2);
M *= M;
}
if (n % 2 == 0) M *= N;
}
</lang>

=== Array (Table) Lookup ===
<lang csharp>
private static int[] fibs = new int[]{ -1836311903, 1134903170,
-701408733, 433494437, -267914296, 165580141, -102334155,
63245986, -39088169, 24157817, -14930352, 9227465, -5702887,
3524578, -2178309, 1346269, -832040, 514229, -317811, 196418,
-121393, 75025, -46368, 28657, -17711, 10946, -6765, 4181,
-2584, 1597, -987, 610, -377, 233, -144, 89, -55, 34, -21, 13,
-8, 5, -3, 2, -1, 1, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711,
28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040,
1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817,
39088169, 63245986, 102334155, 165580141, 267914296, 433494437,
701408733, 1134903170, 1836311903};

public static int Fib(int n) {
if(n < -46 || n > 46) throw new ArgumentOutOfRangeException("n", n, "Has to be between -46 and 47.")
return fibs[n+46];
}
</lang>


=={{header|Cat}}==
=={{header|Cat}}==
<lang cat>define fib {
<syntaxhighlight lang="cat">define fib {
dup 1 <=
dup 1 <=
[]
[]
[dup 1 - fib swap 2 - fib +]
[dup 1 - fib swap 2 - fib +]
if
if
}</lang>
}</syntaxhighlight>


=={{header|Chapel}}==
=={{header|Chapel}}==
<lang chapel>iter fib() {
<syntaxhighlight lang="chapel">iter fib() {
var a = 0, b = 1;
var a = 0, b = 1;


Line 2,133: Line 4,207:
(a, b) = (b, b + a);
(a, b) = (b, b + a);
}
}
}</lang>
}</syntaxhighlight>


=={{header|Chef}}==
=={{header|Chef}}==
<lang chef>Stir-Fried Fibonacci Sequence.
<syntaxhighlight lang="chef">Stir-Fried Fibonacci Sequence.


An unobfuscated iterative implementation.
An unobfuscated iterative implementation.
Line 2,166: Line 4,240:
Pour contents of the 4th mixing bowl into baking dish.
Pour contents of the 4th mixing bowl into baking dish.


Serves 1.</lang>
Serves 1.</syntaxhighlight>


=={{header|CMake}}==
=={{header|Chez Scheme}}==
<syntaxhighlight lang="scheme">
Iteration uses a while() loop. Memoization uses global properties.
(define fib (lambda (n) (cond ((> n 1) (+ (fib (- n 1)) (fib (- n 2))))
((= n 1) 1)
((= n 0) 0))))
</syntaxhighlight>


=={{header|Clio}}==
<lang cmake>set_property(GLOBAL PROPERTY fibonacci_0 0)
set_property(GLOBAL PROPERTY fibonacci_1 1)
set_property(GLOBAL PROPERTY fibonacci_next 2)


Clio is pure and functions are lazy and memoized by default
# var = nth number in Fibonacci sequence.
function(fibonacci var n)
# If the sequence is too short, compute more Fibonacci numbers.
get_property(next GLOBAL PROPERTY fibonacci_next)
if(NOT next GREATER ${n})
# a, b = last 2 Fibonacci numbers
math(EXPR i "${next} - 2")
get_property(a GLOBAL PROPERTY fibonacci_${i})
math(EXPR i "${next} - 1")
get_property(b GLOBAL PROPERTY fibonacci_${i})


<syntaxhighlight lang="clio">fn fib n:
while(NOT next GREATER ${n})
if n < 2: n
math(EXPR i "${a} + ${b}") # i = next Fibonacci number
else: (n - 1 -> fib) + (n - 2 -> fib)
set_property(GLOBAL PROPERTY fibonacci_${next} ${i})
set(a ${b})
set(b ${i})
math(EXPR next "${next} + 1")
endwhile()
set_property(GLOBAL PROPERTY fibonacci_next ${next})
endif()


[0:100] -> * fib -> * print</syntaxhighlight>
get_property(answer GLOBAL PROPERTY fibonacci_${n})
set(${var} ${answer} PARENT_SCOPE)
endfunction(fibonacci)</lang>

<lang cmake># Test program: print 0th to 9th and 25th to 30th Fibonacci numbers.
set(s "")
foreach(i RANGE 0 9)
fibonacci(f ${i})
set(s "${s} ${f}")
endforeach(i)
set(s "${s} ... ")
foreach(i RANGE 25 30)
fibonacci(f ${i})
set(s "${s} ${f}")
endforeach(i)
message(${s})</lang>

<pre> 0 1 1 2 3 5 8 13 21 34 ... 75025 121393 196418 317811 514229 832040</pre>


=={{header|Clojure}}==
=={{header|Clojure}}==
Line 2,219: Line 4,263:
===Lazy Sequence===
===Lazy Sequence===
This is implemented idiomatically as an infinitely long, lazy sequence of all Fibonacci numbers:
This is implemented idiomatically as an infinitely long, lazy sequence of all Fibonacci numbers:
<lang Clojure>(defn fibs []
<syntaxhighlight lang="clojure">(defn fibs []
(map first (iterate (fn [[a b]] [b (+ a b)]) [0 1])))</lang>
(map first (iterate (fn [[a b]] [b (+ a b)]) [0 1])))</syntaxhighlight>
Thus to get the nth one:
Thus to get the nth one:
<lang Clojure>(nth (fibs) 5)</lang>
<syntaxhighlight lang="clojure">(nth (fibs) 5)</syntaxhighlight>
So long as one does not hold onto the head of the sequence, this is unconstrained by length.
So long as one does not hold onto the head of the sequence, this is unconstrained by length.


The one-line implementation may look confusing at first, but on pulling it apart it actually solves the problem more "directly" than a more explicit looping construct.
The one-line implementation may look confusing at first, but on pulling it apart it actually solves the problem more "directly" than a more explicit looping construct.
<lang Clojure>(defn fibs []
<syntaxhighlight lang="clojure">(defn fibs []
(map first ;; throw away the "metadata" (see below) to view just the fib numbers
(map first ;; throw away the "metadata" (see below) to view just the fib numbers
(iterate ;; create an infinite sequence of [prev, curr] pairs
(iterate ;; create an infinite sequence of [prev, curr] pairs
(fn [[a b]] ;; to produce the next pair, call this function on the current pair
(fn [[a b]] ;; to produce the next pair, call this function on the current pair
[b (+ a b)]) ;; new prev is old curr, new curr is sum of both previous numbers
[b (+ a b)]) ;; new prev is old curr, new curr is sum of both previous numbers
[0 1]))) ;; recursive base case: prev 0, curr 1</lang>
[0 1]))) ;; recursive base case: prev 0, curr 1</syntaxhighlight>


A more elegant solution is inspired by the Haskell implementation of an infinite list of Fibonacci numbers:
A more elegant solution is inspired by the Haskell implementation of an infinite list of Fibonacci numbers:
<lang Clojure>(def fib (lazy-cat [0 1] (map + fib (rest fib))))</lang>
<syntaxhighlight lang="clojure">(def fib (lazy-cat [0 1] (map + fib (rest fib))))</syntaxhighlight>
Then, to see the first ten,
Then, to see the first ten,
<lang Clojure>user> (take 10 fib)
<syntaxhighlight lang="clojure">user> (take 10 fib)
(0 1 1 2 3 5 8 13 21 34)</lang>
(0 1 1 2 3 5 8 13 21 34)</syntaxhighlight>


===Iterative===
===Iterative===


Here's a simple interative process (using a recursive function) that carries state along with it (as args) until it reaches a solution:
Here's a simple interative process (using a recursive function) that carries state along with it (as args) until it reaches a solution:
<lang Clojure>;; max is which fib number you'd like computed (0th, 1st, 2nd, etc.)
<syntaxhighlight lang="clojure">;; max is which fib number you'd like computed (0th, 1st, 2nd, etc.)
;; n is which fib number you're on for this call (0th, 1st, 2nd, etc.)
;; n is which fib number you're on for this call (0th, 1st, 2nd, etc.)
;; j is the nth fib number (ex. when n = 5, j = 5)
;; j is the nth fib number (ex. when n = 5, j = 5)
Line 2,259: Line 4,303:
(if (< max 2)
(if (< max 2)
max
max
(fib-iter max 1 0N 1N)))</lang>
(fib-iter max 1 0N 1N)))</syntaxhighlight>
"defn-" means that the function is private (for use only inside this library). The "N" suffixes on integers tell Clojure to use arbitrary precision ints for those.
"defn-" means that the function is private (for use only inside this library). The "N" suffixes on integers tell Clojure to use arbitrary precision ints for those.

===Doubling Algorithm (Fast)===
Based upon the doubling algorithm which computes in O(log (n)) time as described here https://www.nayuki.io/page/fast-fibonacci-algorithms
Implementation credit: https://stackoverflow.com/questions/27466311/how-to-implement-this-fast-doubling-fibonacci-algorithm-in-clojure/27466408#27466408
<syntaxhighlight lang="clojure">
(defn fib [n]
(letfn [(fib* [n]
(if (zero? n)
[0 1]
(let [[a b] (fib* (quot n 2))
c (*' a (-' (*' 2 b) a))
d (+' (*' b b) (*' a a))]
(if (even? n)
[c d]
[d (+' c d)]))))]
(first (fib* n))))
</syntaxhighlight>


===Recursive===
===Recursive===
Line 2,266: Line 4,327:
A naive slow recursive solution:
A naive slow recursive solution:


<lang Clojure>(defn fib [n]
<syntaxhighlight lang="clojure">(defn fib [n]
(case n
(case n
0 0
0 0
1 1
1 1
(+ (fib (- n 1))
(+ (fib (- n 1))
(fib (- n 2)))))</lang>
(fib (- n 2)))))</syntaxhighlight>


This can be improved to an O(n) solution, like the iterative solution, by memoizing the function so that numbers that have been computed are cached. Like a lazy sequence, this also has the advantage that subsequent calls to the function use previously cached results rather than recalculating.
This can be improved to an O(n) solution, like the iterative solution, by memoizing the function so that numbers that have been computed are cached. Like a lazy sequence, this also has the advantage that subsequent calls to the function use previously cached results rather than recalculating.


<lang Clojure>(def fib
<syntaxhighlight lang="clojure">(def fib
(memoize
(memoize
(fn [n]
(fn [n]
Line 2,282: Line 4,343:
1 1
1 1
(+ (fib (- n 1))
(+ (fib (- n 1))
(fib (- n 2)))))))</lang>
(fib (- n 2)))))))</syntaxhighlight>


=== Using core.async ===
=== Using core.async ===
<lang Clojure>(ns fib.core)
<syntaxhighlight lang="clojure">(ns fib.core)
(require '[clojure.core.async
(require '[clojure.core.async
:refer [<! >! >!! <!! timeout chan alt! go]])
:refer [<! >! >!! <!! timeout chan alt! go]])
Line 2,301: Line 4,362:
(for [i (range 10)]
(for [i (range 10)]
(println (<!! c))))))
(println (<!! c))))))
</syntaxhighlight>
</lang>

=={{header|CLU}}==
<syntaxhighlight lang="clu">% Generate Fibonacci numbers
fib = iter () yields (int)
a: int := 0
b: int := 1
while true do
yield (a)
a, b := b, a+b
end
end fib

% Grab the n'th value from an iterator
nth = proc [T: type] (g: itertype () yields (T), n: int) returns (T)
for v: T in g() do
if n<=0 then return (v) end
n := n-1
end
end nth

% Print a few values
start_up = proc ()
po: stream := stream$primary_output()
% print values coming out of the fibonacci iterator
% (which are generated one after the other without delay)
count: int := 0
for f: int in fib() do
stream$putl(po, "F(" || int$unparse(count) || ") = " || int$unparse(f))
count := count + 1
if count = 15 then break end
end
% print a few random fibonacci numbers
% (to do this it has to restart at the beginning for each
% number, making it O(N))
fibs: sequence[int] := sequence[int]$[20,30,50]
for n: int in sequence[int]$elements(fibs) do
stream$putl(po, "F(" || int$unparse(n) || ") = "
|| int$unparse(nth[int](fib, n)))
end
end start_up</syntaxhighlight>
{{out}}
<pre>F(0) = 0
F(1) = 1
F(2) = 1
F(3) = 2
F(4) = 3
F(5) = 5
F(6) = 8
F(7) = 13
F(8) = 21
F(9) = 34
F(10) = 55
F(11) = 89
F(12) = 144
F(13) = 233
F(14) = 377
F(20) = 6765
F(30) = 832040
F(50) = 12586269025</pre>

=={{header|CMake}}==
Iteration uses a while() loop. Memoization uses global properties.

<syntaxhighlight lang="cmake">set_property(GLOBAL PROPERTY fibonacci_0 0)
set_property(GLOBAL PROPERTY fibonacci_1 1)
set_property(GLOBAL PROPERTY fibonacci_next 2)

# var = nth number in Fibonacci sequence.
function(fibonacci var n)
# If the sequence is too short, compute more Fibonacci numbers.
get_property(next GLOBAL PROPERTY fibonacci_next)
if(NOT next GREATER ${n})
# a, b = last 2 Fibonacci numbers
math(EXPR i "${next} - 2")
get_property(a GLOBAL PROPERTY fibonacci_${i})
math(EXPR i "${next} - 1")
get_property(b GLOBAL PROPERTY fibonacci_${i})

while(NOT next GREATER ${n})
math(EXPR i "${a} + ${b}") # i = next Fibonacci number
set_property(GLOBAL PROPERTY fibonacci_${next} ${i})
set(a ${b})
set(b ${i})
math(EXPR next "${next} + 1")
endwhile()
set_property(GLOBAL PROPERTY fibonacci_next ${next})
endif()

get_property(answer GLOBAL PROPERTY fibonacci_${n})
set(${var} ${answer} PARENT_SCOPE)
endfunction(fibonacci)</syntaxhighlight>

<syntaxhighlight lang="cmake"># Test program: print 0th to 9th and 25th to 30th Fibonacci numbers.
set(s "")
foreach(i RANGE 0 9)
fibonacci(f ${i})
set(s "${s} ${f}")
endforeach(i)
set(s "${s} ... ")
foreach(i RANGE 25 30)
fibonacci(f ${i})
set(s "${s} ${f}")
endforeach(i)
message(${s})</syntaxhighlight>

<pre> 0 1 1 2 3 5 8 13 21 34 ... 75025 121393 196418 317811 514229 832040</pre>


=={{header|COBOL}}==
=={{header|COBOL}}==
===Iterative===
===Iterative===
<lang cobol>Program-ID. Fibonacci-Sequence.
<syntaxhighlight lang="cobol">Program-ID. Fibonacci-Sequence.
Data Division.
Data Division.
Working-Storage Section.
Working-Storage Section.
Line 2,344: Line 4,514:
Move INTERM-RESULT to FORMATTED-RESULT.
Move INTERM-RESULT to FORMATTED-RESULT.
Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT.
Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT.
Display FORMATTED-RESULT.</lang>
Display FORMATTED-RESULT.</syntaxhighlight>


===Recursive===
===Recursive===
{{works with|GNU Cobol|2.0}}
{{works with|GNU Cobol|2.0}}
<lang cobol> >>SOURCE FREE
<syntaxhighlight lang="cobol"> >>SOURCE FREE
IDENTIFICATION DIVISION.
IDENTIFICATION DIVISION.
PROGRAM-ID. fibonacci-main.
PROGRAM-ID. fibonacci-main.
Line 2,392: Line 4,562:
END-EVALUATE
END-EVALUATE
.
.
END PROGRAM fibonacci.</lang>
END PROGRAM fibonacci.</syntaxhighlight>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
===Analytic===
===Analytic===
<lang coffeescript>fib_ana = (n) ->
<syntaxhighlight lang="coffeescript">fib_ana = (n) ->
sqrt = Math.sqrt
sqrt = Math.sqrt
phi = ((1 + sqrt(5))/2)
phi = ((1 + sqrt(5))/2)
Math.round((Math.pow(phi, n)/sqrt(5)))</lang>
Math.round((Math.pow(phi, n)/sqrt(5)))</syntaxhighlight>


===Iterative===
===Iterative===
<lang coffeescript>fib_iter = (n) ->
<syntaxhighlight lang="coffeescript">fib_iter = (n) ->
return n if n < 2
return n if n < 2
[prev, curr] = [0, 1]
[prev, curr] = [0, 1]
[prev, curr] = [curr, curr + prev] for i in [1..n]
[prev, curr] = [curr, curr + prev] for i in [1..n]
curr</lang>
curr</syntaxhighlight>


===Recursive===
===Recursive===
<lang coffeescript>fib_rec = (n) ->
<syntaxhighlight lang="coffeescript">fib_rec = (n) ->
if n < 2 then n else fib_rec(n-1) + fib_rec(n-2)</lang>
if n < 2 then n else fib_rec(n-1) + fib_rec(n-2)</syntaxhighlight>


=={{header|Comefrom0x10}}==
=={{header|Comefrom0x10}}==
Line 2,417: Line 4,587:


===Iterative===
===Iterative===
<lang cf0x10>stop = 6
<syntaxhighlight lang="cf0x10">stop = 6
a = 1
a = 1
i = 1 # start
i = 1 # start
Line 2,431: Line 4,601:
b = next_b
b = next_b


comefrom fib if i > stop</lang>
comefrom fib if i > stop</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Note that Common Lisp uses bignums, so this will never overflow.
Note that Common Lisp uses bignums, so this will never overflow.
===Iterative===
===Iterative===
<lang lisp>(defun fibonacci-iterative (n &aux (f0 0) (f1 1))
<syntaxhighlight lang="lisp">(defun fibonacci-iterative (n &aux (f0 0) (f1 1))
(case n
(case n
(0 f0)
(0 f0)
Line 2,443: Line 4,613:
for a = f0 then b and b = f1 then result
for a = f0 then b and b = f1 then result
for result = (+ a b)
for result = (+ a b)
finally (return result)))))</lang>
finally (return result)))))</syntaxhighlight>


Simpler one:
Simpler one:
<lang lisp>(defun fibonacci (n)
<syntaxhighlight lang="lisp">(defun fibonacci (n)
(let ((a 0) (b 1) (c n))
(let ((a 0) (b 1) (c n))
(loop for i from 2 to n do
(loop for i from 2 to n do
Line 2,452: Line 4,622:
a b
a b
b c))
b c))
c))</lang>
c))</syntaxhighlight>


Not a function, just printing out the entire (for some definition of "entire") sequence with a <code>for var = </code> loop:<lang lisp>(loop for x = 0 then y and y = 1 then (+ x y) do (print x))</lang>
Not a function, just printing out the entire (for some definition of "entire") sequence with a <code>for var = </code> loop:<syntaxhighlight lang="lisp">(loop for x = 0 then y and y = 1 then (+ x y) do (print x))</syntaxhighlight>


===Recursive===
===Recursive===
<lang lisp>(defun fibonacci-recursive (n)
<syntaxhighlight lang="lisp">(defun fibonacci-recursive (n)
(if (< n 2)
(if (< n 2)
n
n
(+ (fibonacci-recursive (- n 2)) (fibonacci-recursive (- n 1)))))</lang>
(+ (fibonacci-recursive (- n 2)) (fibonacci-recursive (- n 1)))))</syntaxhighlight>




<lang lisp>(defun fibonacci-tail-recursive ( n &optional (a 0) (b 1))
<syntaxhighlight lang="lisp">(defun fibonacci-tail-recursive ( n &optional (a 0) (b 1))
(if (= n 0)
(if (= n 0)
a
a
(fibonacci-tail-recursive (- n 1) b (+ a b))))</lang>
(fibonacci-tail-recursive (- n 1) b (+ a b))))</syntaxhighlight>


Tail recursive and squaring:
Tail recursive and squaring:
<lang lisp>(defun fib (n &optional (a 1) (b 0) (p 0) (q 1))
<syntaxhighlight lang="lisp">(defun fib (n &optional (a 1) (b 0) (p 0) (q 1))
(if (= n 1) (+ (* b p) (* a q))
(if (= n 1) (+ (* b p) (* a q))
(fib (ash n -1)
(fib (ash n -1)
Line 2,477: Line 4,647:
(+ (* q q) (* 2 p q))))) ;p is Fib(2^n-1), q is Fib(2^n).
(+ (* q q) (* 2 p q))))) ;p is Fib(2^n-1), q is Fib(2^n).


(print (fib 100000))</lang>
(print (fib 100000))</syntaxhighlight>
=== Alternate solution ===
=== Alternate solution ===
I use [https://franz.com/downloads/clp/survey Allegro CL 10.1]
I use [https://franz.com/downloads/clp/survey Allegro CL 10.1]


<lang lisp>
<syntaxhighlight lang="lisp">
;; Project : Fibonacci sequence
;; Project : Fibonacci sequence


Line 2,495: Line 4,665:
(write(+ n 1)) (format t "~a" ": ")
(write(+ n 1)) (format t "~a" ": ")
(write (fibonacci n)) (terpri))
(write (fibonacci n)) (terpri))
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 2,512: Line 4,682:


=== Solution with methods and eql specializers ===
=== Solution with methods and eql specializers ===
<lang lisp>
<syntaxhighlight lang="lisp">
(defmethod fib (n)
(defmethod fib (n)
(declare ((integer 0 *) n))
(declare ((integer 0 *) n))
Line 2,521: Line 4,691:


(defmethod fib ((n (eql 1))) 1)
(defmethod fib ((n (eql 1))) 1)
</syntaxhighlight>
</lang>

=== List-based iterative ===
This solution uses a list to keep track of the Fibonacci sequence for 0 or a
positive integer.
<syntaxhighlight lang="lisp">(defun fibo (n)
(cond ((< n 0) nil)
((< n 2) n)
(t (let ((leo '(1 0)))
(loop for i from 2 upto n do
(setf leo (cons (+ (first leo)
(second leo))
leo))
finally (return (first leo)))))))</syntaxhighlight>

{{out}}
<pre>> (fibo 0)
0
> (fibo 1)
1
> (fibo 10)
55
> (fibo 100)
354224848179261915075
> (fibo 1000)
43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875
> (fibo -10)
NIL</pre>

=== List-based recursive ===
This solution computes Fibonacci numbers as either:

#a list starting from the first element;
#a single number;
#an interval from ''i''-th to ''j''-th element.


Options #2 and #3 can take negative parameters,
but ''i'' (lowest index in range) must be greater
than ''j'' (highest index in range).

Values are represented internally by a reversed
list that grows from the head (and that's why
we reverse it back when we return it).

<syntaxhighlight lang="lisp">(defparameter *fibo-start* '(1 1)) ; elements 1 and 2

;;; Helper functions
(defun grow-fibo (fibo)
(cons (+ (first fibo) (second fibo)) fibo))

(defun generate-fibo (fibo n) ; n must be > 1
(if (equal (list-length fibo) n)
fibo
(generate-fibo (grow-fibo fibo) n)))

;;; User functions
(defun fibo (n)
(cond ((= n 0) 0)
((= (abs n) 1) 1)
(t (let ((result (first (generate-fibo *fibo-start* (abs n)))))
(if (and (< n -1) (evenp n))
(- result)
result)))))

(defun fibo-list (n)
(cond ((< n 1) nil)
((= n 1) '(1))
(t (reverse (generate-fibo *fibo-start* n)))))

(defun fibo-range (lower upper)
(if (<= upper lower)
nil
(reverse (generate-fibo
(list
(fibo (1+ lower))
(fibo lower))
(1+ (- upper lower))))))</syntaxhighlight>
{{out}}
<pre>> (fibo 100)
354224848179261915075
> (fibo -150)
-9969216677189303386214405760200
> (fibo-list 20)
(1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765)
> (fibo-range -10 15)
(-55 34 -21 13 -8 5 -3 2 -1 1 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610)
> (fibo-range 0 20)
(0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765)</pre>


=={{header|Computer/zero Assembly}}==
=={{header|Computer/zero Assembly}}==
To find the <math>n</math>th Fibonacci number, set the initial value of <tt>count</tt> equal to <math>n</math>–2 and run the program. The machine will halt with the answer stored in the accumulator. Since Computer/zero's word length is only eight bits, the program will not work with values of <math>n</math> greater than 13.
To find the <math>n</math>th Fibonacci number, set the initial value of <tt>count</tt> equal to <math>n</math>–2 and run the program. The machine will halt with the answer stored in the accumulator. Since Computer/zero's word length is only eight bits, the program will not work with values of <math>n</math> greater than 13.
<lang czasm>loop: LDA y ; higher No.
<syntaxhighlight lang="czasm">loop: LDA y ; higher No.
STA temp
STA temp
ADD x ; lower No.
ADD x ; lower No.
Line 2,546: Line 4,804:
x: 1
x: 1
y: 1
y: 1
temp: 0</lang>
temp: 0</syntaxhighlight>

=={{header|Coq}}==
<syntaxhighlight lang="coq">
Fixpoint rec_fib (m : nat) (a : nat) (b : nat) : nat :=
match m with
| 0 => a
| S k => rec_fib k b (a + b)
end.

Definition fib (n : nat) : nat :=
rec_fib n 0 1 .
</syntaxhighlight>

=={{header|Corescript}}==
<syntaxhighlight lang="corescript">print Fibonacci Sequence:
var previous = 1
var number = 0
var temp = (blank)

:fib
if number > 50000000000:kill
print (number)
set temp = (add number previous)
set previous = (number)
set number = (temp)
goto fib

:kill
stop</syntaxhighlight>

=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";

sub fibonacci(n: uint32): (a: uint32) is
a := 0;
var b: uint32 := 1;
while n > 0 loop
var c := a + b;
a := b;
b := c;
n := n - 1;
end loop;
end sub;

# test
var i: uint32 := 0;
while i < 20 loop
print_i32(fibonacci(i));
print_char(' ');
i := i + 1;
end loop;
print_nl();</syntaxhighlight>

{{out}}

<pre>0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181</pre>

=={{header|Crystal}}==
===Recursive===
<syntaxhighlight lang="ruby">def fib(n)
n < 2 ? n : fib(n - 1) + fib(n - 2)
end</syntaxhighlight>

===Iterative===
<syntaxhighlight lang="ruby">def fibIterative(n, prevFib = 0, fib = 1)
return n if n < 2

n.times do
prevFib, fib = fib, prevFib + fib
end

prevFib
end</syntaxhighlight>

===Tail Recursive===
<syntaxhighlight lang="ruby">def fibTailRecursive(n, prevFib = 0, fib = 1)
n == 0 ? prevFib : fibTailRecursive(n - 1, fib, prevFib + fib)
end</syntaxhighlight>

===Analytic===
<syntaxhighlight lang="ruby">def fibBinet(n)
(((5 ** 0.5 + 1) / 2) ** n / 5 ** 0.5).round.to_i
end</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
Here are four versions of Fibonacci Number calculating functions. ''FibD'' has an argument limit of magnitude 84 due to floating point precision, the others have a limit of 92 due to overflow (long).The traditional recursive version is inefficient. It is optimized by supplying a static storage to store intermediate results. A Fibonacci Number generating function is added.
Here are four versions of Fibonacci Number calculating functions. ''FibD'' has an argument limit of magnitude 84 due to floating point precision, the others have a limit of 92 due to overflow (long).The traditional recursive version is inefficient. It is optimized by supplying a static storage to store intermediate results. A Fibonacci Number generating function is added.
All functions have support for negative arguments.
All functions have support for negative arguments.
<lang d>import std.stdio, std.conv, std.algorithm, std.math;
<syntaxhighlight lang="d">import std.stdio, std.conv, std.algorithm, std.math;


long sgn(alias unsignedFib)(int n) { // break sign manipulation apart
long sgn(alias unsignedFib)(int n) { // break sign manipulation apart
Line 2,639: Line 4,980:
foreach (i, f; fibG(-9))
foreach (i, f; fibG(-9))
writef("%d:%d | ", i, f);
writef("%d:%d | ", i, f);
}</lang>
}</syntaxhighlight>
{{out}} for n = 85:
{{out}} for n = 85:
<pre>Fib( 85) =
<pre>Fib( 85) =
Line 2,647: Line 4,988:
0:0 | -1:1 | -2:-1 | -3:2 | -4:-3 | -5:5 | -6:-8 | -7:13 | -8:-21 | -9:34 | </pre>
0:0 | -1:1 | -2:-1 | -3:2 | -4:-3 | -5:5 | -6:-8 | -7:13 | -8:-21 | -9:34 | </pre>
===Matrix Exponentiation Version===
===Matrix Exponentiation Version===
<lang d>import std.bigint;
<syntaxhighlight lang="d">import std.bigint;


T fibonacciMatrix(T=BigInt)(size_t n) {
T fibonacciMatrix(T=BigInt)(size_t n) {
Line 2,676: Line 5,017:
void main() {
void main() {
10_000_000.fibonacciMatrix;
10_000_000.fibonacciMatrix;
}</lang>
}</syntaxhighlight>


===Faster Version===
===Faster Version===
For N = 10_000_000 this is about twice faster (run-time about 2.20 seconds) than the matrix exponentiation version.
For N = 10_000_000 this is about twice faster (run-time about 2.20 seconds) than the matrix exponentiation version.
<lang d>import std.bigint, std.math;
<syntaxhighlight lang="d">import std.bigint, std.math;


// Algorithm from: Takahashi, Daisuke,
// Algorithm from: Takahashi, Daisuke,
Line 2,723: Line 5,064:
void main() {
void main() {
10_000_000.fibonacci;
10_000_000.fibonacci;
}</lang>
}</syntaxhighlight>


=={{header|Dart}}==
=={{header|Dart}}==
<lang dart>int fib(int n) {
<syntaxhighlight lang="dart">int fib(int n) {
if (n==0 || n==1) {
if (n==0 || n==1) {
return n;
return n;
Line 2,745: Line 5,086:
print(fib(11));
print(fib(11));
print(fibRec(11));
print(fibRec(11));
}</lang>
}</syntaxhighlight>
=={{header|Datalog}}==
Simple recurive implementation for Souffle.
<syntaxhighlight lang="datalog">.decl Fib(i:number, x:number)
Fib(0, 0).
Fib(1, 1).
Fib(i+2,x+y) :- Fib(i+1, x), Fib(i, y), i+2<=40, i+2>=2.
Fib(i-2,y-x) :- Fib(i-1, x), Fib(i, y), i-2>=-40, i-2<0.</syntaxhighlight>

=={{header|DBL}}==
<syntaxhighlight lang="dart">;
; Fibonacci sequence for DBL version 4 by Dario B.
;
RECORD

FIB1, D10
FIB2, D10
FIBN, D10

J, D5
A2, A2
A5, A5
PROC
;----------------------------------------------------------------
XCALL FLAGS (0007000000,1) ;Suppress STOP message

OPEN (1,O,'TT:')
DISPLAY (1,'First 10 Fibonacci Numbers:',10)
FIB2=1

FOR J=1 UNTIL 10
DO BEGIN
FIBN=FIB1+FIB2

A2=J,'ZX'
A5=FIBN,'ZZZZX'
DISPLAY (1,A2,' : ',A5,10)

FIB1=FIB2
FIB2=FIBN
END
CLOSE 1
END</syntaxhighlight>

=={{header|Dc}}==
This needs a modern Dc with <code>r</code> (swap) and <code>#</code> (comment).
It easily can be adapted to an older Dc, but it will impact readability a lot.
<syntaxhighlight lang="dc">[ # todo: n(<2) -- 1 and break 2 levels
d - # 0
1 + # 1
q
] s1

[ # todo: n(>-1) -- F(n)
d 0=1 # n(!=0)
d 1=1 # n(!in {0,1})
2 - d 1 + # (n-2) (n-1)
lF x # (n-2) F(n-1)
r # F(n-1) (n-2)
lF x # F(n-1)+F(n-2)
+
] sF

33 lF x f</syntaxhighlight>
{{out}}
<pre>
5702887
</pre>


=={{header|Delphi}}==
=={{header|Delphi}}==


=== Iterative ===
=== Iterative ===
<syntaxhighlight lang="delphi">
<lang Delphi>
function FibonacciI(N: Word): UInt64;
function FibonacciI(N: Word): UInt64;
var
var
Line 2,769: Line 5,179:
end;
end;
end;
end;
</syntaxhighlight>
</lang>


=== Recursive ===
=== Recursive ===
<syntaxhighlight lang="delphi">
<lang Delphi>
function Fibonacci(N: Word): UInt64;
function Fibonacci(N: Word): UInt64;
begin
begin
Line 2,780: Line 5,190:
Result := Fibonacci(N - 1) + Fibonacci(N - 2);
Result := Fibonacci(N - 1) + Fibonacci(N - 2);
end;
end;
</syntaxhighlight>
</lang>


=== Matrix ===
=== Matrix ===
Algorithm is based on
Algorithm is based on
:<math>\begin{pmatrix}1&1\\1&0\end{pmatrix}^n = \begin{pmatrix}F(n+1)&F(n)\\F(n)&F(n-1)\end{pmatrix}</math>.
:<math>\begin{pmatrix}1&1\\1&0\end{pmatrix}^n = \begin{pmatrix}F(n+1)&F(n)\\F(n)&F(n-1)\end{pmatrix}</math>.
<syntaxhighlight lang="delphi">
<lang Delphi>
function fib(n: Int64): Int64;
function fib(n: Int64): Int64;


Line 2,822: Line 5,232:
fib := matrix[0,0];
fib := matrix[0,0];
end;
end;
</syntaxhighlight>
</lang>

=={{header|DIBOL-11}}==
<syntaxhighlight lang="dibol-11">

; Redone to include the first two values that
; are noot computed.

START ;First 15 Fibonacci NUmbers


RECORD
FIB1, D10, 0
FIB2, D10, 1
FIBNEW, D10
LOOPCNT, D2, 3

RECORD HEADER
, A32, "First 15 Fibonacci Numbers."

RECORD OUTPUT
LOOPOUT, A2
, A3, " : "
FIBOUT, A10

PROC

OPEN(8,O,'TT:')

WRITES(8,HEADER)

; The First Two are given.

FIBOUT = 0
LOOPOUT = 1
WRITES(8,OUTPUT)
FIBOUT = 1
LOOPOUT = 2
WRITES(8,OUTPUT)

; The Rest are Computed.
LOOP,
FIBNEW = FIB1 + FIB2
LOOPOUT = LOOPCNT, 'ZX'
FIBOUT = FIBNEW, 'ZZZZZZZZZX'

WRITES(8,OUTPUT)

FIB1 = FIB2
FIB2 = FIBNEW
LOOPCNT = LOOPCNT + 1
IF LOOPCNT .LE. 15 GOTO LOOP

CLOSE 8
END



</syntaxhighlight>


=={{header|DWScript}}==
=={{header|DWScript}}==


<lang Delphi>function fib(N : Integer) : Integer;
<syntaxhighlight lang="delphi">function fib(N : Integer) : Integer;
begin
begin
if N < 2 then Result := 1
if N < 2 then Result := 1
else Result := fib(N-2) + fib(N-1);
else Result := fib(N-2) + fib(N-1);
End;</lang>
End;</syntaxhighlight>

=={{header|Dyalect}}==

<syntaxhighlight lang="dyalect">func fib(n) {
if n < 2 {
return n
} else {
return fib(n - 1) + fib(n - 2)
}
}

print(fib(30))</syntaxhighlight>


=={{header|E}}==
=={{header|E}}==
<lang e>def fib(n) {
<syntaxhighlight lang="e">def fib(n) {
var s := [0, 1]
var s := [0, 1]
for _ in 0..!n {
for _ in 0..!n {
Line 2,840: Line 5,323:
}
}
return s[0]
return s[0]
}</lang>
}</syntaxhighlight>


(This version defines <tt>fib(0) = 0</tt> because [http://www.research.att.com/~njas/sequences/A000045 OEIS A000045] does.)
(This version defines <tt>fib(0) = 0</tt> because [http://www.research.att.com/~njas/sequences/A000045 OEIS A000045] does.)

=={{header|EasyLang}}==

<syntaxhighlight lang="text">
func fib n .
if n < 2
return n
.
prev = 0
val = 1
for i = 2 to n
h = prev + val
prev = val
val = h
.
return val
.
print fib 36
</syntaxhighlight>

Recursive (inefficient):

<syntaxhighlight lang="text">
func fib n .
if n < 2
return n
.
return fib (n - 2) + fib (n - 1)
.
print fib 36
</syntaxhighlight>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
Use '''memoization''' with the recursive version.
Use '''memoization''' with the recursive version.
<lang scheme>
<syntaxhighlight lang="scheme">
(define (fib n)
(define (fib n)
(if (< n 2) n
(if (< n 2) n
Line 2,855: Line 5,369:
(for ((i 12)) (write (fib i)))
(for ((i 12)) (write (fib i)))
0 1 1 2 3 5 8 13 21 34 55 89
0 1 1 2 3 5 8 13 21 34 55 89
</syntaxhighlight>
</lang>


=={{header|ECL}}==
=={{header|ECL}}==
Line 2,861: Line 5,375:
===Analytic===
===Analytic===


<lang ECL>//Calculates Fibonacci sequence up to n steps using Binet's closed form solution
<syntaxhighlight lang="ecl">//Calculates Fibonacci sequence up to n steps using Binet's closed form solution




Line 2,889: Line 5,403:
RETURN FibSeq;
RETURN FibSeq;
END; }</lang>
END; }</syntaxhighlight>


=={{header|EDSAC order code}}==
=={{header|EDSAC order code}}==
This program calculates the <i>n</i>th—by default the tenth—number in the Fibonacci sequence and displays it (in binary) in the first word of storage tank 3.
This program calculates the <i>n</i>th—by default the tenth—number in the Fibonacci sequence and displays it (in binary) in the first word of storage tank 3.
<lang edsac>[ Fibonacci sequence
<syntaxhighlight lang="edsac">[ Fibonacci sequence
==================
==================
Line 2,944: Line 5,458:
[ 20 ] P0F [ used to clear a ]
[ 20 ] P0F [ used to clear a ]


EZPF [ begin execution ]</lang>
EZPF [ begin execution ]</syntaxhighlight>
{{out}}
{{out}}
<pre>00000000000110111</pre>
<pre>00000000000110111</pre>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
<lang eiffel>
<syntaxhighlight lang="eiffel">
class
class
APPLICATION
APPLICATION
Line 3,000: Line 5,514:


end
end
</syntaxhighlight>
</lang>


=={{header|Ela}}==
=={{header|Ela}}==
Tail-recursive function:
Tail-recursive function:
<lang Ela>fib = fib' 0 1
<syntaxhighlight lang="ela">fib = fib' 0 1
where fib' a b 0 = a
where fib' a b 0 = a
fib' a b n = fib' b (a + b) (n - 1)</lang>
fib' a b n = fib' b (a + b) (n - 1)</syntaxhighlight>
Infinite (lazy) list:
Infinite (lazy) list:
<lang Ela>fib = fib' 1 1
<syntaxhighlight lang="ela">fib = fib' 1 1
where fib' x y = & x :: fib' y (x + y)</lang>
where fib' x y = & x :: fib' y (x + y)</syntaxhighlight>

=={{header|Elena}}==
=={{header|Elena}}==
{{trans|Smalltalk}}
{{trans|Smalltalk}}
ELENA 3.4 :
ELENA 6.x :
<lang elena>import extensions.
<syntaxhighlight lang="elena">import extensions;

fibu(n)
fibu(n)
{
[
var ac := Array new(2); populate(:i)(i).
int[] ac := new int[]{ 0,1 };
if (n < 2)
if (n < 2)
{
[ ^ ac[n] ];
[
^ ac[n]
}
2 to:n do(:i)
[
else
{
var t := ac[1].
ac[1] := ac[0] + ac[1].
for(int i := 2; i <= n; i+=1)
ac[0] := t.
{
].
int t := ac[1];
ac[1] := ac[0] + ac[1];
^ ac[1]
ac[0] := t
]
};
]
^ ac[1]

}
public program
}
[
0 to:10 do(:i)
public program()
[
{
console printLine(fibu(i)).
for(int i := 0; i <= 10; i+=1)
]
{
]</lang>
console.printLine(fibu(i))
}
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,053: Line 5,571:
55
55
</pre>
</pre>
=== Alternative version using yieldable method ===

<syntaxhighlight lang="elena">import extensions;

public FibonacciGenerator
{
yieldable next()
{
long n_2 := 1l;
long n_1 := 1l;

$yield n_2;
$yield n_1;

while(true)
{
long n := n_2 + n_1;

$yield n;

n_2 := n_1;
n_1 := n
}
}
}

public program()
{
auto e := new FibonacciGenerator();
for(int i := 0; i < 10; i += 1) {
console.printLine(e.next())
};
console.readChar()
}</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang Elixir>defmodule Fibonacci do
<syntaxhighlight lang="elixir">defmodule Fibonacci do
def fib(0), do: 0
def fib(0), do: 0
def fib(1), do: 1
def fib(1), do: 1
Line 3,067: Line 5,621:
end
end


IO.inspect Enum.map(0..10, fn i-> Fibonacci.fib(i) end)</lang>
IO.inspect Enum.map(0..10, fn i-> Fibonacci.fib(i) end)</syntaxhighlight>


Using Stream:
Using Stream:
<syntaxhighlight lang="elixir">
<lang Elixir>
Stream.unfold({0,1}, fn {a,b} -> {a,{b,a+b}} end) |> Enum.take(10)
Stream.unfold({0,1}, fn {a,b} -> {a,{b,a+b}} end) |> Enum.take(10)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,080: Line 5,634:


=={{header|Elm}}==
=={{header|Elm}}==

Naïve recursive implementation.
Naïve recursive implementation.
<lang haskell>fibonacci : Int -> Int
<syntaxhighlight lang="haskell">fibonacci : Int -> Int
fibonacci n = if n < 2 then
fibonacci n = if n < 2 then
n
n
else
else
fibonacci(n - 2) + fibonacci(n - 1)</lang>
fibonacci(n - 2) + fibonacci(n - 1)</syntaxhighlight>


'''version 2'''
<syntaxhighlight lang=”elm">fib : Int -> number
fib n =
case n of
0 -> 0
1 -> 1
_ -> fib (n-1) + fib (n-2)

</syntaxhighlight>
{{out}}
<pre>
elm repl
> fib 40
102334155 : number

> List.map (\elem -> fib elem) (List.range 1 40)
[1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,
4181,6765,10946,17711,28657,46368,75025,121393,196418,
317811,514229,832040,1346269,2178309,3524578,5702887,
9227465,14930352,24157817,39088169,63245986,102334155]
: List number
</pre>


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==

===version 1===
===version 1===
<lang Emacs Lisp>
(defun fib (n a b c)
(if (< c n) (fib n b (+ a b) (+ 1 c) )
(if (= c n) b a) ))


<syntaxhighlight lang="lisp">(defun fib (n a b c)
(defun fibonacci (n) (if (< n 2) n (fib n 0 1 1) ))
(cond
</lang>
((< c n) (fib n b (+ a b) (+ 1 c)))
===version 2===
((= c n) b)
<lang Emacs Lisp>
(t a)))

(defun fibonacci (n)
(defun fibonacci (n)
(let ( (vec) (i) (j) (k) )
(if (< n 2)
(if (< n 2) n
n
(fib n 0 1 1)))</syntaxhighlight>
(progn

(setq vec (make-vector (+ n 1) 0) i 0 j 1 k 2)
===version 2===
(setf (aref vec 1) 1)

(while (<= k n)
<syntaxhighlight lang="lisp">(defun fibonacci (n)
(setf (aref vec k) (+ (elt vec i) (elt vec j) ))
(setq i (+ 1 i) j (+ 1 j) k (+ 1 k) ))
(let (vec i j k)
(elt vec n) ))))
(if (< n 2)
n
</lang>
(setq vec (make-vector (+ n 1) 0)
i 0
j 1
k 2)
(setf (aref vec 1) 1)
(while (<= k n)
(setf (aref vec k) (+ (elt vec i) (elt vec j)))
(setq i (1+ i)
j (1+ j)
k (1+ k)))
(elt vec n))))</syntaxhighlight>

<b>Eval:</b>
<b>Eval:</b>

<lang Emacs Lisp>
<syntaxhighlight lang="lisp">(insert
(insert
(mapconcat '(lambda (n) (format "%d" (fibonacci n) ))
(mapconcat (lambda (n) (format "%d" (fibonacci n)))
(number-sequence 0 15) " ") )
(number-sequence 0 15) " "))</syntaxhighlight>

</lang>
{{out}}
<b>Output:</b>

<pre>
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
</pre>


=={{header|Erlang}}==
=={{header|Erlang}}==
===Recursive ===
===Recursive ===
<syntaxhighlight lang="erlang">
<lang Erlang>
-module(fib).
-module(fib).
-export([fib/1]).
-export([fib/1]).


fib(0) -> 1;
fib(0) -> 0;
fib(1) -> 1;
fib(1) -> 1;
fib(N) -> fib(N-1) + fib(N-2).
fib(N) -> fib(N-1) + fib(N-2).
</syntaxhighlight>
</lang>


===Iterative ===
===Iterative ===
<syntaxhighlight lang="erlang">
<lang Erlang>
-module(fiblin).
-module(fiblin).
-export([fib/1])
-export([fib/1])
Line 3,146: Line 5,735:
fib(N, A, B) -> if N < 1 -> B; true -> fib(N-1, B, A+B) end.
fib(N, A, B) -> if N < 1 -> B; true -> fib(N-1, B, A+B) end.


</syntaxhighlight>
</lang>


<b> Evaluate:</b>
<b> Evaluate:</b>
<syntaxhighlight lang="erlang">
<lang Erlang>
io:write([fiblin:fib(X) || X <- lists:seq(1,10) ]).
io:write([fiblin:fib(X) || X <- lists:seq(1,10) ]).
</syntaxhighlight>
</lang>


<b> Output:</b>
<b> Output:</b>
Line 3,159: Line 5,748:


===Iterative 2===
===Iterative 2===
<syntaxhighlight lang="erlang">
<lang Erlang>
fib(N) -> fib(N, 0, 1).
fib(N) -> fib(N, 0, 1).


Line 3,165: Line 5,754:
fib(Iter, Result, Next) -> fib(Iter-1, Next, Result+Next).
fib(Iter, Result, Next) -> fib(Iter-1, Next, Result+Next).


</syntaxhighlight>
</lang>


=={{header|ERRE}}==
=={{header|ERRE}}==
<lang ERRE>!-------------------------------------------
<syntaxhighlight lang="erre">!-------------------------------------------
! derived from my book "PROGRAMMARE IN ERRE"
! derived from my book "PROGRAMMARE IN ERRE"
! iterative solution
! iterative solution
Line 3,195: Line 5,784:


END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,205: Line 5,794:
==='Recursive' version===
==='Recursive' version===
{{works with|Euphoria|any version}}
{{works with|Euphoria|any version}}
<syntaxhighlight lang="euphoria">
<lang Euphoria>
function fibor(integer n)
function fibor(integer n)
if n<2 then return n end if
if n<2 then return n end if
return fibor(n-1)+fibor(n-2)
return fibor(n-1)+fibor(n-2)
end function
end function
</syntaxhighlight>
</lang>


==='Iterative' version===
==='Iterative' version===
{{works with|Euphoria|any version}}
{{works with|Euphoria|any version}}
<syntaxhighlight lang="euphoria">
<lang Euphoria>
function fiboi(integer n)
function fiboi(integer n)
integer f0=0, f1=1, f
integer f0=0, f1=1, f
Line 3,225: Line 5,814:
return f
return f
end function
end function
</syntaxhighlight>
</lang>


==='Tail recursive' version===
==='Tail recursive' version===
{{works with|Euphoria|4.0.0}}
{{works with|Euphoria|4.0.0}}
<syntaxhighlight lang="euphoria">
<lang Euphoria>
function fibot(integer n, integer u = 1, integer s = 0)
function fibot(integer n, integer u = 1, integer s = 0)
if n < 1 then
if n < 1 then
Line 3,240: Line 5,829:
-- example:
-- example:
? fibot(10) -- says 55
? fibot(10) -- says 55
</syntaxhighlight>
</lang>


==='Paper tape' version===
==='Paper tape' version===
{{works with|Euphoria|4.0.0}}
{{works with|Euphoria|4.0.0}}
<syntaxhighlight lang="euphoria">
<lang Euphoria>
include std/mathcons.e -- for PINF constant
include std/mathcons.e -- for PINF constant


Line 3,324: Line 5,913:
end while
end while


</syntaxhighlight>
</lang>


=={{header|FALSE}}==
=={{header|Excel}}==
===LAMBDA===
<lang false>[[$0=~][1-@@\$@@+\$44,.@]#]f:
Binding the name FIBONACCI to the following lambda in the Excel worksheet Name Manager:
20n: {First 20 numbers}

0 1 n;f;!%%44,. {Output: "0,1,1,2,3,5..."}</lang>
(See [https://www.microsoft.com/en-us/research/blog/lambda-the-ultimatae-excel-worksheet-function/ The LAMBDA worksheet function])

{{Works with|Office 365 Betas 2021}}
<syntaxhighlight lang="lisp">FIBONACCI
=LAMBDA(n,
APPLYN(n - 2)(
LAMBDA(xs,
APPENDROWS(xs)(
SUM(
LASTNROWS(2)(xs)
)
)
)
)({1;1})
)</syntaxhighlight>

And assuming that the following names are also bound to reusable generic lambdas in the Name manager:
<syntaxhighlight lang="lisp">APPENDROWS
=LAMBDA(xs,
LAMBDA(ys,
LET(
nx, ROWS(xs),
rowIndexes, SEQUENCE(nx + ROWS(ys)),
colIndexes, SEQUENCE(
1,
MAX(COLUMNS(xs), COLUMNS(ys))
),

IFERROR(
IF(rowIndexes <= nx,
INDEX(xs, rowIndexes, colIndexes),
INDEX(ys, rowIndexes - nx, colIndexes)
),
NA()
)
)
)
)


APPLYN
=LAMBDA(n,
LAMBDA(f,
LAMBDA(x,
IF(0 < n,
APPLYN(n - 1)(f)(
f(x)
),
x
)
)
)
)

LASTNROWS
=LAMBDA(n,
LAMBDA(xs,
LET(
nRows, COUNTA(xs),
x, MIN(nRows, n),

IF(0 < n,
INDEX(
xs,
SEQUENCE(
x, 1,
1 + nRows - x, 1
)
),
NA()
)
)
)
)</syntaxhighlight>

{{Out}}
The FIBONACCI(n) lambda defines a column of integers.

Here we obtain a row, by composing FIBONACCI with the built-in TRANSPOSE function:
{| class="wikitable"
|-
|||style="text-align:right; font-family:serif; font-style:italic; font-size:120%;"|fx
! colspan="16" style="text-align:left; vertical-align: bottom; font-family:Arial, Helvetica, sans-serif !important;"|=TRANSPOSE(FIBONACCI(15))
|- style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff;"
|
| A
| B
| C
| D
| E
| F
| G
| H
| I
| J
| K
| L
| M
| N
| O
| P
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 2
| style="text-align:left; font-weight:bold" | 15 Fibonacci terms:
| style="text-align:left; background-color:#cbcefb" | 1
| style="text-align:left" | 1
| style="text-align:left" | 2
| style="text-align:left" | 3
| style="text-align:left" | 5
| style="text-align:left" | 8
| style="text-align:left" | 13
| style="text-align:left" | 21
| style="text-align:left" | 34
| style="text-align:left" | 55
| style="text-align:left" | 89
| style="text-align:left" | 144
| style="text-align:left" | 233
| style="text-align:left" | 377
| style="text-align:left" | 610
|}

Or as a fold, obtaining just the Nth term of the Fibonacci series:

<syntaxhighlight lang="lisp">FIBONACCI2
=LAMBDA(n,
INDEX(
FOLDL(
LAMBDA(ab,
LAMBDA(_,
APPEND(INDEX(ab, 2))(SUM(ab))
)
)
)({0;1})(
ENUMFROMTO(1)(n)
),
1
)
)</syntaxhighlight>

Assuming the following generic bindings in the Excel worksheet Name manager:

<syntaxhighlight lang="lisp">APPEND
=LAMBDA(xs,
LAMBDA(ys,
LET(
nx, ROWS(xs),
rowIndexes, SEQUENCE(nx + ROWS(ys)),
colIndexes, SEQUENCE(
1,
MAX(COLUMNS(xs), COLUMNS(ys))
),
IF(rowIndexes <= nx,
INDEX(xs, rowIndexes, colIndexes),
INDEX(ys, rowIndexes - nx, colIndexes)
)
)
)
)


ENUMFROMTO
=LAMBDA(a,
LAMBDA(z,
SEQUENCE(1 + z - a, 1, a, 1)
)
)


FOLDL
=LAMBDA(op,
LAMBDA(a,
LAMBDA(xs,
IF(
2 > ROWS(xs),
op(a)(xs),
FOLDL(op)(
op(a)(
HEAD(xs)
)
)(
TAIL(xs)
)
)
)
)
)


HEAD
=LAMBDA(xs,
INDEX(xs, 1, SEQUENCE(1, COLUMNS(xs)))
)


TAIL
=LAMBDA(xs,
INDEX(
xs,
SEQUENCE(ROWS(xs) - 1, 1, 2, 1),
SEQUENCE(1, COLUMNS(xs))
)
)</syntaxhighlight>
{{Out}}
{| class="wikitable"
|-
|||style="text-align:right; font-family:serif; font-style:italic; font-size:120%;"|fx
! colspan="2" style="text-align:left; vertical-align: bottom; font-family:Arial, Helvetica, sans-serif !important;"|=FIBONACCI2(A2)
|- style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff;"
|
| A
| B
|- style="text-align:right;"
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 1
| style="text-align:right; font-weight:bold" | N
| style="font-weight:bold" | Fibonacci
|- style="text-align:right;"
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 2
| style="text-align:right; font-weight:bold" | 32
| style="background-color:#cbcefb;" | 2178309
|- style="text-align:right;"
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 3
| style="text-align:right; font-weight:bold" | 64
| 10610209857723
|}

=={{header|F_Sharp|F#}}==
This is a fast [tail-recursive] approach using the F# big integer support:
<syntaxhighlight lang="fsharp">
let fibonacci n : bigint =
let rec f a b n =
match n with
| 0 -> a
| 1 -> b
| n -> (f b (a + b) (n - 1))
f (bigint 0) (bigint 1) n
> fibonacci 100;;
val it : bigint = 354224848179261915075I</syntaxhighlight>
Lazy evaluated using sequence workflow:
<syntaxhighlight lang="fsharp">let rec fib = seq { yield! [0;1];
for (a,b) in Seq.zip fib (Seq.skip 1 fib) -> a+b}</syntaxhighlight>

The above is extremely slow due to the nested recursions on sequences, which aren't very efficient at the best of times. The above takes seconds just to compute the 30th Fibonacci number!

Lazy evaluation using the sequence unfold anamorphism is much much better as to efficiency:
<syntaxhighlight lang="fsharp">let fibonacci = Seq.unfold (fun (x, y) -> Some(x, (y, x + y))) (0I,1I)
fibonacci |> Seq.nth 10000
</syntaxhighlight>

Approach similar to the Matrix algorithm in C#, with some shortcuts involved.
Since it uses exponentiation by squaring, calculations of fib(n) where n is a power of 2 are particularly quick.
Eg. fib(2^20) was calculated in a little over 4 seconds on this poster's laptop.
<syntaxhighlight lang="fsharp">
open System
open System.Diagnostics
open System.Numerics

/// Finds the highest power of two which is less than or equal to a given input.
let inline prevPowTwo (x : int) =
let mutable n = x
n <- n - 1
n <- n ||| (n >>> 1)
n <- n ||| (n >>> 2)
n <- n ||| (n >>> 4)
n <- n ||| (n >>> 8)
n <- n ||| (n >>> 16)
n <- n + 1
match x with
| x when x = n -> x
| _ -> n/2

/// Evaluates the nth Fibonacci number using matrix arithmetic and
/// exponentiation by squaring.
let crazyFib (n : int) =
let powTwo = prevPowTwo n

/// Applies 2n rule repeatedly until another application of the rule would
/// go over the target value (or the target value has been reached).
let rec iter1 i q r s =
match i with
| i when i < powTwo ->
iter1 (i*2) (q*q + r*r) (r * (q+s)) (r*r + s*s)
| _ -> i, q, r, s

/// Applies n+1 rule until the target value is reached.
let rec iter2 (i, q, r, s) =
match i with
| i when i < n ->
iter2 ((i+1), (q+r), q, r)
| _ -> q

match n with
| 0 -> 1I
| _ ->
iter1 1 1I 1I 0I
|> iter2
</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
===Iterative===
===Iterative===
<lang factor>: fib ( n -- m )
<syntaxhighlight lang="factor">: fib ( n -- m )
dup 2 < [
dup 2 < [
[ 0 1 ] dip [ swap [ + ] keep ] times
[ 0 1 ] dip [ swap [ + ] keep ] times
drop
drop
] unless ;</lang>
] unless ;</syntaxhighlight>


===Recursive===
===Recursive===
<lang factor>: fib ( n -- m )
<syntaxhighlight lang="factor">: fib ( n -- m )
dup 2 < [
dup 2 < [
[ 1 - fib ] [ 2 - fib ] bi +
[ 1 - fib ] [ 2 - fib ] bi +
] unless ;</lang>
] unless ;</syntaxhighlight>


===Tail-Recursive===
===Tail-Recursive===
<lang factor>: fib2 ( x y n -- a )
<syntaxhighlight lang="factor">: fib2 ( x y n -- a )
dup 1 <
dup 1 <
[ 2drop ]
[ 2drop ]
[ [ swap [ + ] keep ] dip 1 - fib2 ]
[ [ swap [ + ] keep ] dip 1 - fib2 ]
if ;
if ;
: fib ( n -- m ) [ 0 1 ] dip fib2 ;</lang>
: fib ( n -- m ) [ 0 1 ] dip fib2 ;</syntaxhighlight>


===Matrix===
===Matrix===
{{trans|Ruby}}
{{trans|Ruby}}
<lang factor>USE: math.matrices
<syntaxhighlight lang="factor">USE: math.matrices


: fib ( n -- m )
: fib ( n -- m )
Line 3,361: Line 6,264:
[ { { 0 1 } { 1 1 } } ] dip 1 - m^n
[ { { 0 1 } { 1 1 } } ] dip 1 - m^n
second second
second second
] unless ;</lang>
] unless ;</syntaxhighlight>

=={{header|Fancy}}==
<lang fancy>class Fixnum {
def fib {
match self -> {
case 0 -> 0
case 1 -> 1
case _ -> self - 1 fib + (self - 2 fib)
}
}
}

15 times: |x| {
x fib println
}
</lang>


=={{header|Falcon}}==
=={{header|Falcon}}==
===Iterative===
===Iterative===
<lang falcon>function fib_i(n)
<syntaxhighlight lang="falcon">function fib_i(n)


if n < 2: return n
if n < 2: return n
Line 3,393: Line 6,280:
end
end
return fib
return fib
end</lang>
end</syntaxhighlight>
===Recursive===
===Recursive===
<lang falcon>function fib_r(n)
<syntaxhighlight lang="falcon">function fib_r(n)
if n < 2 : return n
if n < 2 : return n
return fib_r(n-1) + fib_r(n-2)
return fib_r(n-1) + fib_r(n-2)
end</lang>
end</syntaxhighlight>
===Tail Recursive===
===Tail Recursive===
<lang falcon>function fib_tr(n)
<syntaxhighlight lang="falcon">function fib_tr(n)
return fib_aux(n,0,1)
return fib_aux(n,0,1)
end
end
Line 3,408: Line 6,295:
default: return fib_aux(n-1,a+b,a)
default: return fib_aux(n-1,a+b,a)
end
end
end</lang>
end</syntaxhighlight>

=={{header|FALSE}}==
<syntaxhighlight lang="false">[[$0=~][1-@@\$@@+\$44,.@]#]f:
20n: {First 20 numbers}
0 1 n;f;!%%44,. {Output: "0,1,1,2,3,5..."}</syntaxhighlight>

=={{header|Fancy}}==
<syntaxhighlight lang="fancy">class Fixnum {
def fib {
match self -> {
case 0 -> 0
case 1 -> 1
case _ -> self - 1 fib + (self - 2 fib)
}
}
}

15 times: |x| {
x fib println
}
</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==
Line 3,414: Line 6,322:
Ints have a limit of 64-bits, so overflow errors occur after computing Fib(92) = 7540113804746346429.
Ints have a limit of 64-bits, so overflow errors occur after computing Fib(92) = 7540113804746346429.


<lang fantom>
<syntaxhighlight lang="fantom">
class Main
class Main
{
{
Line 3,436: Line 6,344:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Fe}}==
Recursive:
<syntaxhighlight lang="clojure">
(= fib (fn (n)
(if (< n 2) n
(+ (fib (- n 1)) (fib (- n 2))))))
</syntaxhighlight>
Iterative:
<syntaxhighlight lang="clojure">
(= fib (fn (n)
(let p0 0)
(let p1 1)
(while (< 0 n)
(= n (- n 1))
(let tmp (+ p0 p1))
(= p0 p1)
(= p1 tmp))
p0))
</syntaxhighlight>

=={{header|Fermat}}==
<syntaxhighlight lang="fermat">Func Fibonacci(n) = if n<0 then -(-1)^n*Fibonacci(-n) else if n<2 then n else
Array fib[n+1];
fib[1] := 0;
fib[2] := 1;
for i = 2, n do
fib[i+1]:=fib[i]+fib[i-1]
od;
Return(fib[n+1]);
fi;
fi;
.</syntaxhighlight>


=={{header|Fexl}}==
=={{header|Fexl}}==


<syntaxhighlight lang="fexl">
<lang Fexl>
# (fib n) = the nth Fibonacci number
# (fib n) = the nth Fibonacci number
\fib=
\fib=
Line 3,458: Line 6,398:
# Now test it:
# Now test it:
for 0 20 (\n say (fib n))
for 0 20 (\n say (fib n))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,484: Line 6,424:
6765
6765
</pre>
</pre>

=={{header|Fish}}==
Outputs Fibonacci numbers until stopped.
<syntaxhighlight lang="fish">10::n' 'o&+&$10.</syntaxhighlight>


=={{header|FOCAL}}==
=={{header|FOCAL}}==
<lang focal>01.10 TYPE "FIBONACCI NUMBERS" !
<syntaxhighlight lang="focal">01.10 TYPE "FIBONACCI NUMBERS" !
01.20 ASK "N =", N
01.20 ASK "N =", N
01.30 SET A=0
01.30 SET A=0
Line 3,496: Line 6,440:
02.10 SET T=B
02.10 SET T=B
02.20 SET B=A+B
02.20 SET B=A+B
02.30 SET A=T</lang>
02.30 SET A=T</syntaxhighlight>
{{out}}
{{out}}
<pre>FIBONACCI NUMBERS
<pre>FIBONACCI NUMBERS
Line 3,503: Line 6,447:


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>: fib ( n -- fib )
<syntaxhighlight lang="forth">: fib ( n -- fib )
0 1 rot 0 ?do over + swap loop drop ;</lang>
0 1 rot 0 ?do over + swap loop drop ;</syntaxhighlight>

Or, for negative-index support:

<syntaxhighlight lang="forth">: fib ( n -- Fn ) 0 1 begin
rot dup 0 = if drop drop exit then
dup 0 > if 1 - rot rot dup rot +
else 1 + rot rot over - swap then
again ;</syntaxhighlight>


Since there are only a fixed and small amount of Fibonacci numbers that fit in a machine word, this FORTH version creates a table of Fibonacci numbers at compile time. It stops compiling numbers when there is arithmetic overflow (the number turns negative, indicating overflow.)
Since there are only a fixed and small amount of Fibonacci numbers that fit in a machine word, this FORTH version creates a table of Fibonacci numbers at compile time. It stops compiling numbers when there is arithmetic overflow (the number turns negative, indicating overflow.)


<lang forth>: F-start, here 1 0 dup , ;
<syntaxhighlight lang="forth">: F-start, here 1 0 dup , ;
: F-next, over + swap
: F-next, over + swap
dup 0> IF dup , true ELSE false THEN ;
dup 0> IF dup , true ELSE false THEN ;
Line 3,524: Line 6,476:
16 fibonacci . 987 ok
16 fibonacci . 987 ok
#F/64 . 93 ok
#F/64 . 93 ok
92 fibonacci . 7540113804746346429 ok \ largest number generated.</lang>
92 fibonacci . 7540113804746346429 ok \ largest number generated.</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
===FORTRAN IV===
===FORTRAN IV===
<lang fortran>C FIBONACCI SEQUENCE - FORTRAN IV
<syntaxhighlight lang="fortran">C FIBONACCI SEQUENCE - FORTRAN IV
NN=46
NN=46
DO 1 I=0,NN
DO 1 I=0,NN
Line 3,549: Line 6,501:
5 IFN=IFNM1+IFNM2
5 IFN=IFNM1+IFNM2
9 IFIBO=IFN
9 IFIBO=IFN
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,568: Line 6,520:
</pre>
</pre>
===FORTRAN 77===
===FORTRAN 77===
<lang fortran>
<syntaxhighlight lang="fortran">
FUNCTION IFIB(N)
FUNCTION IFIB(N)
IF (N.EQ.0) THEN
IF (N.EQ.0) THEN
Line 3,593: Line 6,545:
IFIB=ITEMP0
IFIB=ITEMP0
END
END
</syntaxhighlight>
</lang>
Test program
Test program
<lang fortran>
<syntaxhighlight lang="fortran">
EXTERNAL IFIB
EXTERNAL IFIB
CHARACTER*10 LINE
CHARACTER*10 LINE
Line 3,607: Line 6,559:
901 FORMAT(3(X,I10))
901 FORMAT(3(X,I10))
END
END
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,627: Line 6,579:
===Recursive===
===Recursive===
In ISO Fortran 90 or later, use a RECURSIVE function:
In ISO Fortran 90 or later, use a RECURSIVE function:
<lang fortran>module fibonacci
<syntaxhighlight lang="fortran">module fibonacci
contains
contains
recursive function fibR(n) result(fib)
recursive function fibR(n) result(fib)
Line 3,638: Line 6,590:
case default; fib = fibR(n-1) + fibR(n-2)
case default; fib = fibR(n-1) + fibR(n-2)
end select
end select
end function fibR</lang>
end function fibR</syntaxhighlight>
===Iterative===
===Iterative===
In ISO Fortran 90 or later:
In ISO Fortran 90 or later:
<lang fortran> function fibI(n)
<syntaxhighlight lang="fortran"> function fibI(n)
integer, intent(in) :: n
integer, intent(in) :: n
integer, parameter :: fib0 = 0, fib1 = 1
integer, parameter :: fib0 = 0, fib1 = 1
Line 3,660: Line 6,612:
end select
end select
end function fibI
end function fibI
end module fibonacci</lang>
end module fibonacci</syntaxhighlight>


Test program
Test program
<lang fortran>program fibTest
<syntaxhighlight lang="fortran">program fibTest
use fibonacci
use fibonacci
Line 3,669: Line 6,621:
print *, fibr(i), fibi(i)
print *, fibr(i), fibi(i)
end do
end do
end program fibTest</lang>
end program fibTest</syntaxhighlight>


{{out}}
{{out}}
Line 3,686: Line 6,638:
</pre>
</pre>


=={{header|FreeBASIC}}==
=={{header|Free Pascal}}==
''See also: [[#Pascal|Pascal]]''
Extended sequence coded big integer.
<syntaxhighlight lang="pascal">type
<lang FreeBASIC>'Fibonacci extended
/// domain for Fibonacci function
'Freebasic version 24 Windows
/// where result is within nativeUInt
Dim Shared ADDQmod(0 To 19) As Ubyte
// You can not name it fibonacciDomain,
Dim Shared ADDbool(0 To 19) As Ubyte
// since the Fibonacci function itself
// is defined for all whole numbers
// but the result beyond F(n) exceeds high(nativeUInt).
fibonacciLeftInverseRange =
{$ifdef CPU64} 0..93 {$else} 0..47 {$endif};


{**
For z As Integer=0 To 19
implements Fibonacci sequence iteratively
ADDQmod(z)=(z Mod 10+48)
ADDbool(z)=(-(10<=z))
\param n the index of the Fibonacci number to calculate
Next z
\returns the Fibonacci value at n

}
Function plusINT(NUM1 As String,NUM2 As String) As String
function fibonacci(const n: fibonacciLeftInverseRange): nativeUInt;
Dim As Byte flag
type
#macro finish()
/// more meaningful identifiers than simple integers
three=Ltrim(three,"0")
relativePosition = (previous, current, next);
If three="" Then Return "0"
var
If flag=1 Then Swap NUM2,NUM1
/// temporary iterator variable
Return three
i: longword;
Exit Function
/// holds preceding fibonacci values
#endmacro
f: array[relativePosition] of nativeUInt;
var lenf=Len(NUM1)
begin
var lens=Len(NUM2)
f[previous] := 0;
If lens>lenf Then
f[current] := 1;
Swap NUM2,NUM1
Swap lens,lenf
// note, in Pascal for-loop-limits are inclusive
flag=1
End If
for i := 1 to n do
begin
f[next] := f[previous] + f[current];
var diff=lenf-lens-Sgn(lenf-lens)
f[previous] := f[current];
var three="0"+NUM1
f[current] := f[next];
var two=String(lenf-lens,"0")+NUM2
end;
Dim As Integer n2
Dim As Ubyte addup,addcarry
// assign to previous, bc f[current] = f[next] for next iteration
fibonacci := f[previous];
addcarry=0
end;</syntaxhighlight>
For n2=lenf-1 To diff Step -1
addup=two[n2]+NUM1[n2]-96
three[n2+1]=addQmod(addup+addcarry)
addcarry=addbool(addup+addcarry)
Next n2
If addcarry=0 Then
finish()
End If
If n2=-1 Then
three[0]=addcarry+48
finish()
End If
For n2=n2 To 0 Step -1
addup=two[n2]+NUM1[n2]-96
three[n2+1]=addQmod(addup+addcarry)
addcarry=addbool(addup+addcarry)
Next n2
three[0]=addcarry+48
finish()
End Function

Function fibonacci(n As Integer) As String
Dim As String sl,l,term
sl="0": l="1"
If n=1 Then Return "0"
If n=2 Then Return "1"
n=n-2
For x As Integer= 1 To n
term=plusINT(l,sl)
sl=l
l=term
Next x
Function =term
End Function

'============== EXAMPLE ===============
print "THE SEQUENCE TO 10:"
print
For n As Integer=1 To 10
Print "term";n;": "; fibonacci(n)
Next n
print
print "Selected Fibonacci number"
print "Fibonacci 500"
print
print fibonacci(500)
Sleep</lang>
{{out}}
<pre>THE SEQUENCE TO 10:

term 1: 0
term 2: 1
term 3: 1
term 4: 2
term 5: 3
term 6: 5
term 7: 8
term 8: 13
term 9: 21
term 10: 34

Selected Fibonacci number
Fibonacci 500

86168291600238450732788312165664788095941068326060883324529903470149056115823592
713458328176574447204501</pre>


=={{header|Frink}}==
=={{header|Frink}}==
All of Frink's integers can be arbitrarily large.
All of Frink's integers can be arbitrarily large.
<lang frink>
<syntaxhighlight lang="frink">
fibonacciN[n] :=
fibonacciN[n] :=
{
{
Line 3,806: Line 6,696:
return a
return a
}
}
</syntaxhighlight>
</lang>


=={{header|FRISC Assembly}}==
=={{header|FRISC Assembly}}==
To find the nth Fibonacci number, call this subroutine with n in register R0: the answer will be returned in R0 too. Contents of other registers are preserved.
To find the nth Fibonacci number, call this subroutine with n in register R0: the answer will be returned in R0 too. Contents of other registers are preserved.
<lang friscasm>FIBONACCI PUSH R1
<syntaxhighlight lang="friscasm">FIBONACCI PUSH R1
PUSH R2
PUSH R2
PUSH R3
PUSH R3
Line 3,832: Line 6,722:
POP R1
POP R1


RET</lang>
RET</syntaxhighlight>

=={{header|F_Sharp|F#}}==
This is a fast [tail-recursive] approach using the F# big integer support:
<lang fsharp>
let fibonacci n : bigint =
let rec f a b n =
match n with
| 0 -> a
| 1 -> b
| n -> (f b (a + b) (n - 1))
f (bigint 0) (bigint 1) n
> fibonacci 100;;
val it : bigint = 354224848179261915075I</lang>
Lazy evaluated using sequence workflow:
<lang fsharp>let rec fib = seq { yield! [0;1];
for (a,b) in Seq.zip fib (Seq.skip 1 fib) -> a+b}</lang>

The above is extremely slow due to the nested recursions on sequences, which aren't very efficient at the best of times. The above takes seconds just to compute the 30th Fibonacci number!

Lazy evaluation using the sequence unfold anamorphism is much much better as to efficiency:
<lang fsharp>let fibonacci = Seq.unfold (fun (x, y) -> Some(x, (y, x + y))) (0I,1I)
fibonacci |> Seq.nth 10000
</lang>

Approach similar to the Matrix algorithm in C#, with some shortcuts involved.
Since it uses exponentiation by squaring, calculations of fib(n) where n is a power of 2 are particularly quick.
Eg. fib(2^20) was calculated in a little over 4 seconds on this poster's laptop.
<lang fsharp>
open System
open System.Diagnostics
open System.Numerics

/// Finds the highest power of two which is less than or equal to a given input.
let inline prevPowTwo (x : int) =
let mutable n = x
n <- n - 1
n <- n ||| (n >>> 1)
n <- n ||| (n >>> 2)
n <- n ||| (n >>> 4)
n <- n ||| (n >>> 8)
n <- n ||| (n >>> 16)
n <- n + 1
match x with
| x when x = n -> x
| _ -> n/2

/// Evaluates the nth Fibonacci number using matrix arithmetic and
/// exponentiation by squaring.
let crazyFib (n : int) =
let powTwo = prevPowTwo n

/// Applies 2n rule repeatedly until another application of the rule would
/// go over the target value (or the target value has been reached).
let rec iter1 i q r s =
match i with
| i when i < powTwo ->
iter1 (i*2) (q*q + r*r) (r * (q+s)) (r*r + s*s)
| _ -> i, q, r, s

/// Applies n+1 rule until the target value is reached.
let rec iter2 (i, q, r, s) =
match i with
| i when i < n ->
iter2 ((i+1), (q+r), q, r)
| _ -> q

match n with
| 0 -> 1I
| _ ->
iter1 1 1I 1I 0I
|> iter2
</lang>


=={{header|FunL}}==
=={{header|FunL}}==
=== Recursive ===
=== Recursive ===
<lang funl>def
<syntaxhighlight lang="funl">def
fib( 0 ) = 0
fib( 0 ) = 0
fib( 1 ) = 1
fib( 1 ) = 1
fib( n ) = fib( n - 1 ) + fib( n - 2 )</lang>
fib( n ) = fib( n - 1 ) + fib( n - 2 )</syntaxhighlight>


=== Tail Recursive ===
=== Tail Recursive ===
<lang funl>def fib( n ) =
<syntaxhighlight lang="funl">def fib( n ) =
def
def
_fib( 0, prev, _ ) = prev
_fib( 0, prev, _ ) = prev
Line 3,920: Line 6,738:
_fib( n, prev, next ) = _fib( n - 1, next, next + prev )
_fib( n, prev, next ) = _fib( n - 1, next, next + prev )


_fib( n, 0, 1 )</lang>
_fib( n, 0, 1 )</syntaxhighlight>


=== Lazy List ===
=== Lazy List ===
<lang funl>val fib =
<syntaxhighlight lang="funl">val fib =
def _fib( a, b ) = a # _fib( b, a + b )
def _fib( a, b ) = a # _fib( b, a + b )


_fib( 0, 1 )
_fib( 0, 1 )


println( fib(10000) )</lang>
println( fib(10000) )</syntaxhighlight>


{{out}}
{{out}}
Line 3,937: Line 6,755:


=== Iterative ===
=== Iterative ===
<lang funl>def fib( n ) =
<syntaxhighlight lang="funl">def fib( n ) =
a, b = 0, 1
a, b = 0, 1


Line 3,943: Line 6,761:
a, b = b, a+b
a, b = b, a+b


a</lang>
a</syntaxhighlight>


=== Binet's Formula ===
=== Binet's Formula ===
<lang funl>import math.sqrt
<syntaxhighlight lang="funl">import math.sqrt


def fib( n ) =
def fib( n ) =
phi = (1 + sqrt( 5 ))/2
phi = (1 + sqrt( 5 ))/2
int( (phi^n - (-phi)^-n)/sqrt(5) + .5 )</lang>
int( (phi^n - (-phi)^-n)/sqrt(5) + .5 )</syntaxhighlight>


=== Matrix Exponentiation ===
=== Matrix Exponentiation ===
<lang funl>def mul( a, b ) =
<syntaxhighlight lang="funl">def mul( a, b ) =
res = array( a.length(), b(0).length() )
res = array( a.length(), b(0).length() )


Line 3,971: Line 6,789:


for i <- 0..10
for i <- 0..10
println( fib(i) )</lang>
println( fib(i) )</syntaxhighlight>


{{out}}
{{out}}
Line 3,993: Line 6,811:
=== Iterative ===
=== Iterative ===


<syntaxhighlight lang="futhark">
<lang Futhark>
fun main(n: int): int =
fun main(n: int): int =
loop((a,b) = (0,1)) = for _i < n do
loop((a,b) = (0,1)) = for _i < n do
(b, a + b)
(b, a + b)
in a
in a
</syntaxhighlight>
</lang>


=={{header|FutureBasic}}==
=={{header|FutureBasic}}==
=== Iterative ===
=== Iterative ===
<syntaxhighlight lang="futurebasic">window 1, @"Fibonacci Sequence", (0,0,480,620)
<lang futurebasic>
include "Tlbx Timer.incl"
include "ConsoleWindow"


local fn Fibonacci( n as long ) as Long
local fn Fibonacci( n as long ) as long
static long s1
begin globals
dim as long s1, s2// static
static long s2
long temp
end globals

if ( n < 2 )
dim as long temp
s1 = n

if ( n < 2 )
exit fn
s1 = n
else
temp = s1 + s2
exit fn
s2 = s1
else
temp = s1 + s2
s1 = temp
s2 = s1
exit fn
s1 = temp
end if
exit fn
end if
end fn = s1
end fn = s1


dim as long i
long i
CFTimeInterval t
dim as UnsignedWide start, finish

t = fn CACurrentMediaTime


Microseconds( @start )
for i = 0 to 40
for i = 0 to 40
print i; ". "; fn Fibonacci(i)
print i;@".\t";fn Fibonacci(i)
next i
next i

Microseconds( @finish )
print "Compute time:"; (finish.lo - start.lo ) / 1000; " ms"
print : printf @"Compute time: %.3f ms",(fn CACurrentMediaTime-t)*1000

</lang>
HandleEvents</syntaxhighlight>
Output:
Output:
<pre>
<pre>
0. 0
0. 0
1. 1
1. 1
2. 1
2. 1
3. 2
3. 2
4. 3
4. 3
5. 5
5. 5
6. 8
6. 8
7. 13
7. 13
8. 21
8. 21
9. 34
9. 34
10. 55
10. 55
11. 89
11. 89
12. 144
12. 144
13. 233
13. 233
14. 377
14. 377
15. 610
15. 610
16. 987
16. 987
17. 1597
17. 1597
18. 2584
18. 2584
19. 4181
19. 4181
20. 6765
20. 6765
21. 10946
21. 10946
22. 17711
22. 17711
23. 28657
23. 28657
24. 46368
24. 46368
25. 75025
25. 75025
26. 121393
26. 121393
27. 196418
27. 196418
28. 317811
28. 317811
29. 514229
29. 514229
30. 832040
30. 832040
31. 1346269
31. 1346269
32. 2178309
32. 2178309
33. 3524578
33. 3524578
34. 5702887
34. 5702887
35. 9227465
35. 9227465
36. 14930352
36. 14930352
37. 24157817
37. 24157817
38. 39088169
38. 39088169
39. 63245986
39. 63245986
40. 102334155
40. 102334155

41. 165580141
Compute time: 2.143 ms</pre>
42. 267914296

43. 433494437
=== Recursive ===
44. 701408733
Cost is a time penalty
45. 1134903170
<syntaxhighlight lang="futurebasic">
46. 1836311903
local fn Fibonacci( n as NSInteger ) as NSInteger
47. 2971215073
NSInteger result
48. 4.80752698e+9
if n < 2 then result = n : exit fn
49. 7.77874205e+9
result = fn Fibonacci( n-1 ) + fn Fibonacci( n-2 )
50. 1.2586269e+10
end fn = result
51. 2.03650111e+10

52. 3.29512801e+10
window 1
53. 5.33162912e+10

54. 8.62675713e+10
NSInteger i
55. 1.39583862e+11
CFTimeInterval t
56. 2.25851434e+11

57. 3.65435296e+11
t = fn CACurrentMediaTime
58. 5.9128673e+11
for i = 0 to 40
59. 9.56722026e+11
print i;@".\t";fn Fibonacci(i)
60. 1.54800876e+12
next
61. 2.50473078e+12
print : printf @"Compute time: %.3f ms",(fn CACurrentMediaTime-t)*1000
62. 4.05273954e+12

63. 6.55747032e+12
HandleEvents
64. 1.06102099e+13
</syntaxhighlight>
65. 1.71676802e+13
{{output}}
66. 2.777789e+13
<pre>
67. 4.49455702e+13
0. 0
68. 7.27234602e+13
1. 1
69. 1.1766903e+14
2. 1
70. 1.90392491e+14
3. 2
71. 3.08061521e+14
4. 3
72. 4.98454012e+14
5. 5
73. 8.06515533e+14
6. 8
74. 1.30496954e+15
7. 13
75. 2.11148508e+15
8. 21
76. 3.41645462e+15
9. 34
77. 5.5279397e+15
10. 55
78. 8.94439432e+15
11. 89
79. 1.4472334e+16
12. 144
80. 2.34167283e+16
13. 233
81. 3.78890624e+16
14. 377
82. 6.13057907e+16
15. 610
83. 9.91948531e+16
16. 987
84. 1.60500644e+17
17. 1597
85. 2.59695497e+17
18. 2584
86. 4.20196141e+17
19. 4181
87. 6.79891638e+17
20. 6765
88. 1.10008778e+18
21. 10946
89. 1.77997942e+18
22. 17711
90. 2.88006719e+18
23. 28657
91. 4.66004661e+18
24. 46368
92. 7.5401138e+18
25. 75025
93. 1.22001604e+19
26. 121393
94. 1.97402742e+19
27. 196418
95. 3.19404346e+19
28. 317811
96. 5.16807089e+19
29. 514229
97. 8.36211435e+19
30. 832040
98. 1.35301852e+20
31. 1346269
99. 2.18922996e+20
32. 2178309
100. 3.54224848e+20
33. 3524578
Compute time: 15 ms
34. 5702887
35. 9227465
36. 14930352
37. 24157817
38. 39088169
39. 63245986
40. 102334155

Compute time: 2844.217 ms
</pre>
</pre>

=={{header|Fōrmulæ}}==

{{FormulaeEntry|page=https://formulae.org/?script=examples/Fibonacci_numbers}}

=== Recursive ===

Recursive version is slow, it is O(2<sup>n</sup>), or of exponential order.

[[File:Fōrmulæ - Fibonacci sequence 01.png]]

[[File:Fōrmulæ - Fibonacci sequence 02.png]]

[[File:Fōrmulæ - Fibonacci sequence result.png]]

It is because it makes a lot of recursive calls.

To illustrate this, the following is a functions that makes a tree or the recursive calls:

[[File:Fōrmulæ - Fibonacci sequence 03.png]]

[[File:Fōrmulæ - Fibonacci sequence 04.png]]

[[File:Fōrmulæ - Fibonacci sequence 05.png]]

=== Iterative (3 variables) ===

It is O(n), or of linear order.

[[File:Fōrmulæ - Fibonacci sequence 06.png]]

[[File:Fōrmulæ - Fibonacci sequence 07.png]]

[[File:Fōrmulæ - Fibonacci sequence result.png]]

=== Iterative (2 variables) ===

It is O(n), or of linear order.

[[File:Fōrmulæ - Fibonacci sequence 08.png]]

[[File:Fōrmulæ - Fibonacci sequence 09.png]]

[[File:Fōrmulæ - Fibonacci sequence result.png]]

=== Iterative, using a list ===

It is O(n), or of linear order.

[[File:Fōrmulæ - Fibonacci sequence 10.png]]

[[File:Fōrmulæ - Fibonacci sequence 11.png]]

[[File:Fōrmulæ - Fibonacci sequence result.png]]

=== Using matrix multiplication ===

[[File:Fōrmulæ - Fibonacci sequence 12.png]]

[[File:Fōrmulæ - Fibonacci sequence 13.png]]

[[File:Fōrmulæ - Fibonacci sequence result.png]]

=== Divide and conquer ===

It is an optimized version of the matrix multiplication algorithm, with an order of O(lg(n))

[[File:Fōrmulæ - Fibonacci sequence 14.png]]

[[File:Fōrmulæ - Fibonacci sequence 15.png]]

[[File:Fōrmulæ - Fibonacci sequence result.png]]

=== Closed-form ===

It has an order of O(lg(n))

[[File:Fōrmulæ - Fibonacci sequence 16.png]]

[[File:Fōrmulæ - Fibonacci sequence 17.png]]

[[File:Fōrmulæ - Fibonacci sequence result.png]]


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap>fib := function(n)
<syntaxhighlight lang="gap">fib := function(n)
local a;
local a;
a := [[0, 1], [1, 1]]^n;
a := [[0, 1], [1, 1]]^n;
return a[1][2];
return a[1][2];
end;</lang>
end;</syntaxhighlight>
GAP has also a buit-in function for that.
GAP has also a buit-in function for that.
<lang gap>Fibonacci(n);</lang>
<syntaxhighlight lang="gap">Fibonacci(n);</syntaxhighlight>


=={{header|Gecho}}==
=={{header|Gecho}}==
<lang gecho>0 1 dup wover + dup wover + dup wover + dup wover +</lang>
<syntaxhighlight lang="gecho">0 1 dup wover + dup wover + dup wover + dup wover +</syntaxhighlight>
Prints the first several fibonacci numbers...
Prints the first several fibonacci numbers...

=={{header|GFA Basic}}==

<lang>
'
' Compute nth Fibonacci number
'
' open a window for display
OPENW 1
CLEARW 1
' Display some fibonacci numbers
' Fib(46) is the largest number GFA Basic can reach
' (long integers are 4 bytes)
FOR i%=0 TO 46
PRINT "fib(";i%;")=";@fib(i%)
NEXT i%
' wait for a key press and tidy up
~INP(2)
CLOSEW 1
'
' Function to compute nth fibonacci number
' n must be in range 0 to 46, inclusive
'
FUNCTION fib(n%)
LOCAL n0%,n1%,nn%,i%
n0%=0
n1%=1
SELECT n%
CASE 0
RETURN n0%
CASE 1
RETURN n1%
DEFAULT
FOR i%=2 TO n%
nn%=n0%+n1%
n0%=n1%
n1%=nn%
NEXT i%
RETURN nn%
ENDSELECT
ENDFUNC
</lang>


=={{header|GML}}==
=={{header|GML}}==
<syntaxhighlight lang="gml">///fibonacci(n)

<lang gml>///fibonacci(n)
//Returns the nth fibonacci number
//Returns the nth fibonacci number


Line 4,221: Line 7,085:
}
}


return numb;</lang>
return numb;</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
=== Recursive ===
=== Recursive ===
<lang go>func fib(a int) int {
<syntaxhighlight lang="go">func fib(a int) int {
if a < 2 {
if a < 2 {
return a
return a
}
}
return fib(a - 1) + fib(a - 2)
return fib(a - 1) + fib(a - 2)
}</lang>
}</syntaxhighlight>
=== Iterative ===
=== Iterative ===
<lang go>import (
<syntaxhighlight lang="go">import (
"math/big"
"math/big"
)
)
Line 4,246: Line 7,110:
}
}
return b
return b
}</lang>
}</syntaxhighlight>
=== Iterative using a closure ===
=== Iterative using a closure ===
<lang go>func fibNumber() func() int {
<syntaxhighlight lang="go">func fibNumber() func() int {
fib1, fib2 := 0, 1
fib1, fib2 := 0, 1
return func() int {
return func() int {
Line 4,263: Line 7,127:
}
}
return fib
return fib
}</lang>
}</syntaxhighlight>
=== Using a goroutine and channel ===
=== Using a goroutine and channel ===
<lang go>func fib(c chan int) {
<syntaxhighlight lang="go">func fib(c chan int) {
a, b := 0, 1
a, b := 0, 1
for {
for {
Line 4,280: Line 7,144:
}
}
}
}
</syntaxhighlight>
</lang>

=={{header|Grain}}==
=== Recursive ===
<syntaxhighlight lang="haskell">
import String from "string"
import File from "sys/file"
let rec fib = n => if (n < 2) {
n
} else {
fib(n - 1) + fib(n - 2)
}
for (let mut i = 0; i <= 20; i += 1) {
File.fdWrite(File.stdout, Pervasives.toString(fib(i)))
ignore(File.fdWrite(File.stdout, " "))
}
</syntaxhighlight>
=== Iterative ===
<syntaxhighlight lang="haskell">
import File from "sys/file"
let fib = j => {
let mut fnow = 0, fnext = 1
for (let mut n = 0; n <= j; n += 1) {
if (n == 0 || n == 1) {
let output1 = " " ++ toString(n)
ignore(File.fdWrite(File.stdout, output1))
} else {
let tempf = fnow + fnext
fnow = fnext
fnext = tempf
let output2 = " " ++ toString(fnext)
ignore(File.fdWrite(File.stdout, output2))
}
}
}
fib(20)
</syntaxhighlight>
{{out}}
=== Iterative with Buffer ===
<syntaxhighlight lang="haskell">
import Buffer from "buffer"
import String from "string"
let fib = j => {
// set-up minimal, growable buffer
let buf = Buffer.make(j * 2)
let mut fnow = 0, fnext = 1
for (let mut n = 0; n <= j; n += 1) {
if (n == 0 || n == 1) {
Buffer.addChar(' ', buf)
Buffer.addString(toString(n), buf)
} else {
let tempf = fnow + fnext
fnow = fnext
fnext = tempf
Buffer.addChar(' ', buf)
Buffer.addString(toString(fnext), buf)
}
}
// stringify buffer and return
Buffer.toString(buf)
}
let output = fib(20)
print(output)
</syntaxhighlight>
{{out}}<pre>
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
</pre>


=={{header|Groovy}}==
=={{header|Groovy}}==
Line 4,286: Line 7,216:
=== Recursive ===
=== Recursive ===
A recursive closure must be ''pre-declared''.
A recursive closure must be ''pre-declared''.
<lang groovy>def rFib
<syntaxhighlight lang="groovy">def rFib
rFib = {
rFib = {
it == 0 ? 0
it == 0 ? 0
Line 4,293: Line 7,223:
/*it < 0*/: rFib(it+2) - rFib(it+1)
/*it < 0*/: rFib(it+2) - rFib(it+1)
}</lang>
}</syntaxhighlight>


=== Iterative ===
=== Iterative ===
<lang groovy>def iFib = {
<syntaxhighlight lang="groovy">def iFib = {
it == 0 ? 0
it == 0 ? 0
: it == 1 ? 1
: it == 1 ? 1
: it > 1 ? (2..it).inject([0,1]){i, j -> [i[1], i[0]+i[1]]}[1]
: it > 1 ? (2..it).inject([0,1]){i, j -> [i[1], i[0]+i[1]]}[1]
/*it < 0*/: (-1..it).inject([0,1]){i, j -> [i[1]-i[0], i[0]]}[0]
/*it < 0*/: (-1..it).inject([0,1]){i, j -> [i[1]-i[0], i[0]]}[0]
}</lang>
}</syntaxhighlight>


=== Analytic ===
=== Analytic ===
<lang groovy>final φ = (1 + 5**(1/2))/2
<syntaxhighlight lang="groovy">final φ = (1 + 5**(1/2))/2
def aFib = { (φ**it - (-φ)**(-it))/(5**(1/2)) as BigInteger }</lang>
def aFib = { (φ**it - (-φ)**(-it))/(5**(1/2)) as BigInteger }</syntaxhighlight>


Test program:
Test program:
<lang groovy>def time = { Closure c ->
<syntaxhighlight lang="groovy">def time = { Closure c ->
def start = System.currentTimeMillis()
def start = System.currentTimeMillis()
def result = c()
def result = c()
Line 4,323: Line 7,253:
fibList.each { printf ' %3d', it }
fibList.each { printf ' %3d', it }
println()
println()
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 4,334: Line 7,264:
=={{header|Harbour}}==
=={{header|Harbour}}==
===Recursive===
===Recursive===
<syntaxhighlight lang="harbour">
<lang Harbour>
#include "harbour.ch"
#include "harbour.ch"
Function fibb(a,b,n)
Function fibb(a,b,n)
return(if(--n>0,fibb(b,a+b,n),a))
return(if(--n>0,fibb(b,a+b,n),a))
</syntaxhighlight>
</lang>


===Iterative===
===Iterative===
<syntaxhighlight lang="harbour">
<lang Harbour>
#include "harbour.ch"
#include "harbour.ch"
Function fibb(n)
Function fibb(n)
Line 4,351: Line 7,281:
end while
end while
return(fnext)
return(fnext)
</syntaxhighlight>
</lang>


=={{header|Haskell}}==
=={{header|Haskell}}==
===Analytic===
===Analytic===
{{Works with|exact-real|0.12.5.1}}
<lang haskell>main :: IO ()
Using Binet's formula and [https://hackage.haskell.org/package/exact-real-0.12.5.1/docs/Data-CReal.html exact real arithmetic] library we can calculate arbitrary Fibonacci number '''exactly'''.
main =
<syntaxhighlight lang="haskell">
print
import Data.CReal
[ floor (0.01 + (1 / p ** n + p ** n) / sqrt 5)

| let p = (1 + sqrt 5) / 2
phi = (1 + sqrt 5) / 2
, n <- [0 .. 42] ]</lang>

fib :: (Integral b) => b -> CReal 0
fib n = (phi^^n - (-phi)^^(-n))/sqrt 5
</syntaxhighlight>
Let's try it for large numbers:
<syntaxhighlight lang="haskell">
λ> fib 10 :: CReal 0
55
(0.01 secs, 137,576 bytes)
λ> fib 100 :: CReal 0
354224848179261915075
(0.01 secs, 253,152 bytes)
λ> fib 10000 :: CReal 0
33644764876431783266621612005107543310302148460680063906564769974680081442166662368155595513633734025582065332680836159373734790483865268263040892463056431887354544369559827491606602099884183933864652731300088830269235673613135117579297437854413752130520504347701602264758318906527890855154366159582987279682987510631200575428783453215515103870818298969791613127856265033195487140214287532698187962046936097879900350962302291026368131493195275630227837628441540360584402572114334961180023091208287046088923962328835461505776583271252546093591128203925285393434620904245248929403901706233888991085841065183173360437470737908552631764325733993712871937587746897479926305837065742830161637408969178426378624212835258112820516370298089332099905707920064367426202389783111470054074998459250360633560933883831923386783056136435351892133279732908133732642652633989763922723407882928177953580570993691049175470808931841056146322338217465637321248226383092103297701648054726243842374862411453093812206564914032751086643394517512161526545361333111314042436854805106765843493523836959653428071768775328348234345557366719731392746273629108210679280784718035329131176778924659089938635459327894523777674406192240337638674004021330343297496902028328145933418826817683893072003634795623117103101291953169794607632737589253530772552375943788434504067715555779056450443016640119462580972216729758615026968443146952034614932291105970676243268515992834709891284706740862008587135016260312071903172086094081298321581077282076353186624611278245537208532365305775956430072517744315051539600905168603220349163222640885248852433158051534849622434848299380905070483482449327453732624567755879089187190803662058009594743150052402532709746995318770724376825907419939632265984147498193609285223945039707165443156421328157688908058783183404917434556270520223564846495196112460268313970975069382648706613264507665074611512677522748621598642530711298441182622661057163515069260029861704945425047491378115154139941550671256271197133252763631939606902895650288268608362241082050562430701794976171121233066073310059947366875
(0.02 secs, 4,847,128 bytes)
λ> fib (-10) :: CReal 0
-55
(0.01 secs, 138,408 bytes)
</syntaxhighlight>


===Recursive===
===Recursive===
Simple definition, very inefficient.
Simple definition, very inefficient.


<lang haskell>fib x =
<syntaxhighlight lang="haskell">fib x =
if x < 1
if x < 1
then 0
then 0
else if x < 2
else if x < 2
then 1
then 1
else fib (x - 1) + fib (x - 2)</lang>
else fib (x - 1) + fib (x - 2)</syntaxhighlight>


===Recursive with Memoization===
===Recursive with Memoization===
Very fast.
Very fast.
<lang haskell>fib x =
<syntaxhighlight lang="haskell">fib x =
if x < 1
if x < 1
then 0
then 0
Line 4,381: Line 7,330:
else fibs !! (x - 1) + fibs !! (x - 2)
else fibs !! (x - 1) + fibs !! (x - 2)
where
where
fibs = map fib [0 ..]</lang>
fibs = map fib [0 ..]</syntaxhighlight>


===Recursive with Memoization using memoized library===
===Recursive with Memoization using memoized library===
Even faster and simpler is to use a defined memoizer (e.g. from MemoTrie package):
Even faster and simpler is to use a defined memoizer (e.g. from MemoTrie package):
<lang haskell>import Data.MemoTrie
<syntaxhighlight lang="haskell">import Data.MemoTrie
fib :: Integer -> Integer
fib :: Integer -> Integer
fib = memo f where
fib = memo f where
f 0 = 0
f 0 = 0
f 1 = 1
f 1 = 1
f n = fib (n-1) + fib (n-2)</lang>
f n = fib (n-1) + fib (n-2)</syntaxhighlight>
You can rewrite this without introducing f explicitly
You can rewrite this without introducing f explicitly
<lang haskell>import Data.MemoTrie
<syntaxhighlight lang="haskell">import Data.MemoTrie
fib :: Integer -> Integer
fib :: Integer -> Integer
fib = memo $ \x -> case x of
fib = memo $ \x -> case x of
0 -> 0
0 -> 0
1 -> 1
1 -> 1
n -> fib (n-1) + fib (n-2)</lang>
n -> fib (n-1) + fib (n-2)</syntaxhighlight>
Or using LambdaCase extension you can write it even shorter:
Or using LambdaCase extension you can write it even shorter:
<lang haskell>{-# Language LambdaCase #-}
<syntaxhighlight lang="haskell">{-# Language LambdaCase #-}
import Data.MemoTrie
import Data.MemoTrie
fib :: Integer -> Integer
fib :: Integer -> Integer
Line 4,405: Line 7,354:
0 -> 0
0 -> 0
1 -> 1
1 -> 1
n -> fib (n-1) + fib (n-2)</lang>
n -> fib (n-1) + fib (n-2)</syntaxhighlight>
The version that supports negative numbers:
The version that supports negative numbers:
<lang haskell>{-# Language LambdaCase #-}
<syntaxhighlight lang="haskell">{-# Language LambdaCase #-}
import Data.MemoTrie
import Data.MemoTrie
fib :: Integer -> Integer
fib :: Integer -> Integer
Line 4,414: Line 7,363:
1 -> 1
1 -> 1
n | n>0 -> fib (n-1) + fib (n-2)
n | n>0 -> fib (n-1) + fib (n-2)
| otherwise -> fib (n+2) - fib (n+1)</lang>
| otherwise -> fib (n+2) - fib (n+1)</syntaxhighlight>


===Iterative===
===Iterative===
<lang haskell>fib n = go n 0 1
<syntaxhighlight lang="haskell">fib n = go n 0 1
where
where
go n a b
go n a b
| n == 0 = a
| n == 0 = a
| otherwise = go (n - 1) b (a + b)</lang>
| otherwise = go (n - 1) b (a + b)</syntaxhighlight>


==== With lazy lists ====
==== With lazy lists ====
This is a standard example how to use lazy lists. Here's the (infinite) list of all Fibonacci numbers:
This is a standard example how to use lazy lists. Here's the (infinite) list of all Fibonacci numbers:


<lang haskell>fib = 0 : 1 : zipWith (+) fib (tail fib)</lang>
<syntaxhighlight lang="haskell">fib = 0 : 1 : zipWith (+) fib (tail fib)</syntaxhighlight>
Or alternatively:
Or alternatively:
<lang haskell>fib = 0 : 1 : (zipWith (+) <*> tail) fib </lang>
<syntaxhighlight lang="haskell">fib = 0 : 1 : (zipWith (+) <*> tail) fib </syntaxhighlight>


The ''n''th Fibonacci number is then just <code plang="haskell">fib !! n</code>. The above is equivalent to
The ''n''th Fibonacci number is then just <code plang="haskell">fib !! n</code>. The above is equivalent to


<lang haskell>fib = 0 : 1 : next fib where next (a: t@(b:_)) = (a+b) : next t</lang>
<syntaxhighlight lang="haskell">fib = 0 : 1 : next fib where next (a: t@(b:_)) = (a+b) : next t</syntaxhighlight>


Also
Also


<lang haskell>fib = 0 : scanl (+) 1 fib</lang>
<syntaxhighlight lang="haskell">fib = 0 : scanl (+) 1 fib</syntaxhighlight>


==== As a fold ====
==== As a fold ====
Accumulator holds last two members of the series:
Accumulator holds last two members of the series:


<lang haskell>import Data.List (foldl') --'
<syntaxhighlight lang="haskell">import Data.List (foldl') --'


fib :: Integer -> Integer
fib :: Integer -> Integer
Line 4,449: Line 7,398:
(\(a, b) _ -> (b, a + b))
(\(a, b) _ -> (b, a + b))
(0, 1)
(0, 1)
[1 .. n]</lang>
[1 .. n]</syntaxhighlight>


=== With matrix exponentiation ===
=== With matrix exponentiation ===
Line 4,455: Line 7,404:
we can simply write:
we can simply write:


<lang haskell>import Data.List (transpose)
<syntaxhighlight lang="haskell">import Data.List (transpose)


fib
fib
Line 4,498: Line 7,447:
-- TEST ----------------------------------------------------------------------
-- TEST ----------------------------------------------------------------------
main :: IO ()
main :: IO ()
main = (print . take 10 . show . fib) (10 ^ 5)</lang>
main = (print . take 10 . show . fib) (10 ^ 5)</syntaxhighlight>


So, for example, the hundred-thousandth Fibonacci number starts with the digits:
So, for example, the hundred-thousandth Fibonacci number starts with the digits:
Line 4,506: Line 7,455:
=== With recurrence relations ===
=== With recurrence relations ===
Using <code>Fib[m=3n+r]</code> [http://en.wikipedia.org/wiki/Fibonacci_number#Other_identities recurrence identities]:
Using <code>Fib[m=3n+r]</code> [http://en.wikipedia.org/wiki/Fibonacci_number#Other_identities recurrence identities]:
<lang haskell>import Control.Arrow ((&&&))
<syntaxhighlight lang="haskell">import Control.Arrow ((&&&))


fibstep :: (Integer, Integer) -> (Integer, Integer)
fibstep :: (Integer, Integer) -> (Integer, Integer)
Line 4,540: Line 7,489:


main :: IO ()
main :: IO ()
main = print $ (length &&& take 20) . show . fst $ fibN2 (10 ^ 2)</lang>
main = print $ (length &&& take 20) . show . fst $ fibN2 (10 ^ 2)</syntaxhighlight>
{{Out}}
{{Out}}
<pre>(21,"35422484817926191507")</pre>
<pre>(21,"35422484817926191507")</pre>


<code>(fibN2 n)</code> directly calculates a pair <code>(f,g)</code> of two consecutive Fibonacci numbers, <code>(Fib[n], Fib[n+1])</code>, from recursively calculated such pair at about <code>n/3</code>:
<code>(fibN2 n)</code> directly calculates a pair <code>(f,g)</code> of two consecutive Fibonacci numbers, <code>(Fib[n], Fib[n+1])</code>, from recursively calculated such pair at about <code>n/3</code>:
<lang haskell> *Main> (length &&& take 20) . show . fst $ fibN2 (10^6)
<syntaxhighlight lang="haskell"> *Main> (length &&& take 20) . show . fst $ fibN2 (10^6)
(208988,"19532821287077577316")</lang>
(208988,"19532821287077577316")</syntaxhighlight>
The above should take less than 0.1s to calculate on a modern box.
The above should take less than 0.1s to calculate on a modern box.


Other identities that could also be used are [http://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form here]. In particular, for <i>(n-1,n) ---> (2n-1,2n)</i> transition which is equivalent to the matrix exponentiation scheme, we have
Other identities that could also be used are [http://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form here]. In particular, for <i>(n-1,n) ---> (2n-1,2n)</i> transition which is equivalent to the matrix exponentiation scheme, we have


<lang haskell>f (n,(a,b)) = (2*n,(a*a+b*b,2*a*b+b*b)) -- iterate f (1,(0,1)) ; b is nth</lang>
<syntaxhighlight lang="haskell">f (n,(a,b)) = (2*n,(a*a+b*b,2*a*b+b*b)) -- iterate f (1,(0,1)) ; b is nth</syntaxhighlight>


and for <i>(n,n+1) ---> (2n,2n+1)</i> (derived from d'Ocagne's identity, for example),
and for <i>(n,n+1) ---> (2n,2n+1)</i> (derived from d'Ocagne's identity, for example),


<lang haskell>g (n,(a,b)) = (2*n,(2*a*b-a*a,a*a+b*b)) -- iterate g (1,(1,1)) ; a is nth</lang>
<syntaxhighlight lang="haskell">g (n,(a,b)) = (2*n,(2*a*b-a*a,a*a+b*b)) -- iterate g (1,(1,1)) ; a is nth</syntaxhighlight>


=={{header|Haxe}}==
=={{header|Haxe}}==
=== Iterative ===
=== Iterative ===


<lang haxe>static function fib(steps:Int, handler:Int->Void)
<syntaxhighlight lang="haxe">static function fib(steps:Int, handler:Int->Void)
{
{
var current = 0;
var current = 0;
Line 4,574: Line 7,523:
}
}
handler(current);
handler(current);
}</lang>
}</syntaxhighlight>


=== As Iterator ===
=== As Iterator ===
<lang haxe>class FibIter
<syntaxhighlight lang="haxe">class FibIter
{
{
private var current = 0;
private var current = 0;
Line 4,595: Line 7,544:
return ret;
return ret;
}
}
}</lang>
}</syntaxhighlight>


Used like:
Used like:
<lang haxe>for (i in new FibIter(10))
<syntaxhighlight lang="haxe">for (i in new FibIter(10))
Sys.println(i);</lang>
Sys.println(i);</syntaxhighlight>

=={{header|HicEst}}==
<syntaxhighlight lang="hicest">REAL :: Fibonacci(10)

Fibonacci = ($==2) + Fibonacci($-1) + Fibonacci($-2)
WRITE(ClipBoard) Fibonacci ! 0 1 1 2 3 5 8 13 21 34</syntaxhighlight>

=={{header|Hoon}}==
<syntaxhighlight lang="hoon">|= n=@ud
=/ a=@ud 0
=/ b=@ud 1
|-
?: =(n 0) a
$(a b, b (add a b), n (dec n))</syntaxhighlight>


=={{header|Hope}}==
=={{header|Hope}}==
===Recursive===
===Recursive===
<lang hope>dec f : num -> num;
<syntaxhighlight lang="hope">dec f : num -> num;
--- f 0 <= 0;
--- f 0 <= 0;
--- f 1 <= 1;
--- f 1 <= 1;
--- f(n+2) <= f n + f(n+1);</lang>
--- f(n+2) <= f n + f(n+1);</syntaxhighlight>


===Tail-recursive===
===Tail-recursive===
<lang hope>dec fib : num -> num;
<syntaxhighlight lang="hope">dec fib : num -> num;
--- fib n <= l (1, 0, n)
--- fib n <= l (1, 0, n)
whererec l == \(a,b,succ c) => if c<1 then a else l((a+b),a,c)
whererec l == \(a,b,succ c) => if c<1 then a else l((a+b),a,c)
|(a,b,0) => 0;</lang>
|(a,b,0) => 0;</syntaxhighlight>


=== With lazy lists ===
=== With lazy lists ===
This language, being one of Haskell's ancestors, also has lazy lists. Here's the (infinite) list of all Fibonacci numbers:
This language, being one of Haskell's ancestors, also has lazy lists. Here's the (infinite) list of all Fibonacci numbers:
<lang hope>dec fibs : list num;
<syntaxhighlight lang="hope">dec fibs : list num;
--- fibs <= fs whererec fs == 0::1::map (+) (tail fs||fs);</lang>
--- fibs <= fs whererec fs == 0::1::map (+) (tail fs||fs);</syntaxhighlight>
The ''n''th Fibonacci number is then just <code plang="hope">fibs @ n</code>.
The ''n''th Fibonacci number is then just <code plang="hope">fibs @ n</code>.

=={{header|HicEst}}==
<lang hicest>REAL :: Fibonacci(10)

Fibonacci = ($==2) + Fibonacci($-1) + Fibonacci($-2)
WRITE(ClipBoard) Fibonacci ! 0 1 1 2 3 5 8 13 21 34</lang>


=={{header|Hy}}==
=={{header|Hy}}==
Recursive implementation.
Recursive implementation.
<lang clojure>(defn fib [n]
<syntaxhighlight lang="clojure">(defn fib [n]
(if (< n 2)
(if (< n 2)
n
n
(+ (fib (- n 2)) (fib (- n 1)))))</lang>
(+ (fib (- n 2)) (fib (- n 1)))))</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Line 4,637: Line 7,594:
computes fib(1000) if there is no integer argument.
computes fib(1000) if there is no integer argument.


<lang Icon>procedure main(args)
<syntaxhighlight lang="icon">procedure main(args)
write(fib(integer(!args) | 1000)
write(fib(integer(!args) | 1000)
end
end
Line 4,650: Line 7,607:
/fCache[n] := fib(n-1) + fib(n-2)
/fCache[n] := fib(n-1) + fib(n-2)
return fCache[n]
return fCache[n]
end</lang>
end</syntaxhighlight>
{{libheader|Icon Programming Library}}
{{libheader|Icon Programming Library}}
The above solution is similar to the one provided [http://www.cs.arizona.edu/icon/library/src/procs/memrfncs.icn fib in memrfncs]
The above solution is similar to the one provided [http://www.cs.arizona.edu/icon/library/src/procs/memrfncs.icn fib in memrfncs]
Line 4,659: Line 7,616:
This example computes fib(1000000) if there is no integer argument.
This example computes fib(1000000) if there is no integer argument.


<lang Icon>procedure main(args)
<syntaxhighlight lang="icon">procedure main(args)
write(fib(integer(!args) | 1000000))
write(fib(integer(!args) | 1000000))
end
end
Line 4,675: Line 7,632:
if n%2 = 1 then return [c+d, d]
if n%2 = 1 then return [c+d, d]
else return [d, c]
else return [d, c]
end</lang>
end</syntaxhighlight>


=={{header|IDL}}==
=={{header|IDL}}==
===Recursive===
===Recursive===
<lang idl>function fib,n
<syntaxhighlight lang="idl">function fib,n
if n lt 3 then return,1L else return, fib(n-1)+fib(n-2)
if n lt 3 then return,1L else return, fib(n-1)+fib(n-2)
end</lang>
end</syntaxhighlight>


Execution time O(2^n) until memory is exhausted and your machine starts swapping. Around fib(35) on a 2GB Core2Duo.
Execution time O(2^n) until memory is exhausted and your machine starts swapping. Around fib(35) on a 2GB Core2Duo.


===Iterative===
===Iterative===
<lang idl>function fib,n
<syntaxhighlight lang="idl">function fib,n
psum = (csum = 1uL)
psum = (csum = 1uL)
if n lt 3 then return,csum
if n lt 3 then return,csum
Line 4,695: Line 7,652:
endfor
endfor
return,nsum
return,nsum
end</lang>
end</syntaxhighlight>


Execution time O(n). Limited by size of uLong to fib(49)
Execution time O(n). Limited by size of uLong to fib(49)


===Analytic===
===Analytic===
<lang idl>function fib,n
<syntaxhighlight lang="idl">function fib,n
q=1/( p=(1+sqrt(5))/2 )
q=1/( p=(1+sqrt(5))/2 )
return,round((p^n+q^n)/sqrt(5))
return,round((p^n+q^n)/sqrt(5))
end</lang>
end</syntaxhighlight>


Execution time O(1), only limited by the range of LongInts to fib(48).
Execution time O(1), only limited by the range of LongInts to fib(48).
Line 4,710: Line 7,667:


===Analytic===
===Analytic===
<lang idris>fibAnalytic : Nat -> Double
<syntaxhighlight lang="idris">fibAnalytic : Nat -> Double
fibAnalytic n =
fibAnalytic n =
floor $ ((pow goldenRatio n) - (pow (-1.0/goldenRatio) n)) / sqrt(5)
floor $ ((pow goldenRatio n) - (pow (-1.0/goldenRatio) n)) / sqrt(5)
where goldenRatio : Double
where goldenRatio : Double
goldenRatio = (1.0 + sqrt(5)) / 2.0</lang>
goldenRatio = (1.0 + sqrt(5)) / 2.0</syntaxhighlight>
===Recursive===
===Recursive===
<lang idris>fibRecursive : Nat -> Nat
<syntaxhighlight lang="idris">fibRecursive : Nat -> Nat
fibRecursive Z = Z
fibRecursive Z = Z
fibRecursive (S Z) = (S Z)
fibRecursive (S Z) = (S Z)
fibRecursive (S (S n)) = fibRecursive (S n) + fibRecursive n </lang>
fibRecursive (S (S n)) = fibRecursive (S n) + fibRecursive n </syntaxhighlight>
===Iterative===
===Iterative===
<lang idris>fibIterative : Nat -> Nat
<syntaxhighlight lang="idris">fibIterative : Nat -> Nat
fibIterative n = fibIterative' n Z (S Z)
fibIterative n = fibIterative' n Z (S Z)
where fibIterative' : Nat -> Nat -> Nat -> Nat
where fibIterative' : Nat -> Nat -> Nat -> Nat
fibIterative' Z a _ = a
fibIterative' Z a _ = a
fibIterative' (S n) a b = fibIterative' n b (a + b) </lang>
fibIterative' (S n) a b = fibIterative' n b (a + b) </syntaxhighlight>
===Lazy===
===Lazy===
<lang idris>fibLazy : Lazy (List Nat)
<syntaxhighlight lang="idris">fibLazy : Lazy (List Nat)
fibLazy = 0 :: 1 :: zipWith (+) fibLazy (
fibLazy = 0 :: 1 :: zipWith (+) fibLazy (
case fibLazy of
case fibLazy of
(x::xs) => xs
(x::xs) => xs
[] => []) </lang>
[] => []) </syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
The [[j:Essays/Fibonacci_Sequence|Fibonacci Sequence essay]] on the J Wiki presents a number of different ways of obtaining the nth Fibonacci number. Here is one:
The [https://code.jsoftware.com/wiki/Essays/Fibonacci_Sequence Fibonacci Sequence essay] on the J Wiki presents a number of different ways of obtaining the nth Fibonacci number.

<lang j> fibN=: (-&2 +&$: -&1)^:(1&<) M."0</lang>
This implementation is doubly recursive except that results are cached across function calls:
<syntaxhighlight lang="j">fibN=: (-&2 +&$: <:)^:(1&<) M."0</syntaxhighlight>
Iteration:
<syntaxhighlight lang="j">fibN=: [: {."1 +/\@|.@]^:[&0 1</syntaxhighlight>
'''Examples:'''
'''Examples:'''
<lang j> fibN 12
<syntaxhighlight lang="j"> fibN 12
144
144
fibN i.31
fibN i.31
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040</lang>
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040</syntaxhighlight>

(This implementation is doubly recursive except that results are cached across function calls.)


=={{header|Java}}==
=={{header|Java}}==
===Iterative===
===Iterative===
<lang java>public static long itFibN(int n)
<syntaxhighlight lang="java">public static long itFibN(int n)
{
{
if (n < 2)
if (n < 2)
Line 4,760: Line 7,719:
}
}
return ans;
return ans;
}</lang>
}</syntaxhighlight>


<lang java>
<syntaxhighlight lang="java">
/**
/**
* O(log(n))
* O(log(n))
Line 4,791: Line 7,750:
return a + b;
return a + b;
}
}
</syntaxhighlight>
</lang>


===Recursive===
===Recursive===
<lang java>public static long recFibN(final int n)
<syntaxhighlight lang="java">public static long recFibN(final int n)
{
{
return (n < 2) ? n : recFibN(n - 1) + recFibN(n - 2);
return (n < 2) ? n : recFibN(n - 1) + recFibN(n - 2);
}</lang>
}</syntaxhighlight>

===Caching-recursive===
A variant on recursive, that caches previous results, reducing complexity from O(n<sup>2</sup>) to simply O(n). Leveraging Java’s Map.computeIfAbsent makes this thread-safe, and the implementation pretty trivial.
<syntaxhighlight lang="java">public class Fibonacci {

static final Map<Integer, Long> cache = new HashMap<>();
static {
cache.put(1, 1L);
cache.put(2, 1L);
}

public static long get(int n)
{
return (n < 2) ? n : impl(n);
}
private static long impl(int n)
{
return cache.computeIfAbsent(n, k -> impl(k-1) + impl(k-2));
}
}</syntaxhighlight>
===Analytic===
===Analytic===
This method works up to the 92<sup>nd</sup> Fibonacci number. After that, it goes out of range.
This method works up to the 92<sup>nd</sup> Fibonacci number. After that, it goes out of range.
<lang java>public static long anFibN(final long n)
<syntaxhighlight lang="java">public static long anFibN(final long n)
{
{
double p = (1 + Math.sqrt(5)) / 2;
double p = (1 + Math.sqrt(5)) / 2;
double q = 1 / p;
double q = 1 / p;
return (long) ((Math.pow(p, n) + Math.pow(q, n)) / Math.sqrt(5));
return (long) ((Math.pow(p, n) + Math.pow(q, n)) / Math.sqrt(5));
}</lang>
}</syntaxhighlight>
===Tail-recursive===
===Tail-recursive===
<lang java>public static long fibTailRec(final int n)
<syntaxhighlight lang="java">public static long fibTailRec(final int n)
{
{
return fibInner(0, 1, n);
return fibInner(0, 1, n);
Line 4,815: Line 7,795:
{
{
return n < 1 ? a : n == 1 ? b : fibInner(b, a + b, n - 1);
return n < 1 ? a : n == 1 ? b : fibInner(b, a + b, n - 1);
}</lang>
}</syntaxhighlight>
===Streams===
===Streams===
<lang java5>
<syntaxhighlight lang="java5">
import java.util.function.LongUnaryOperator;
import java.util.function.LongUnaryOperator;
import java.util.stream.LongStream;
import java.util.stream.LongStream;
Line 4,836: Line 7,816:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 4,842: Line 7,822:
====Recursive====
====Recursive====
Basic recursive function:
Basic recursive function:
<lang javascript>function fib(n) {
<syntaxhighlight lang="javascript">function fib(n) {
return n<2?n:fib(n-1)+fib(n-2);
return n<2?n:fib(n-1)+fib(n-2);
}</lang>
}</syntaxhighlight>
Can be rewritten as:
Can be rewritten as:
<lang javascript>function fib(n) {
<syntaxhighlight lang="javascript">function fib(n) {
if (n<2) { return n; } else { return fib(n-1)+fib(n-2); }
if (n<2) { return n; } else { return fib(n-1)+fib(n-2); }
}</lang>
}</syntaxhighlight>


One possibility familiar to Scheme programmers is to define an internal function for iteration through anonymous tail recursion:
One possibility familiar to Scheme programmers is to define an internal function for iteration through anonymous tail recursion:
<lang javascript>function fib(n) {
<syntaxhighlight lang="javascript">function fib(n) {
return function(n,a,b) {
return function(n,a,b) {
return n>0 ? arguments.callee(n-1,b,a+b) : a;
return n>0 ? arguments.callee(n-1,b,a+b) : a;
}(n,0,1);
}(n,0,1);
}</lang>
}</syntaxhighlight>


===Iterative===
===Iterative===
<lang javascript>function fib(n) {
<syntaxhighlight lang="javascript">function fib(n) {
var a = 0, b = 1, t;
var a = 0, b = 1, t;
while (n-- > 0) {
while (n-- > 0) {
Line 4,867: Line 7,847:
}
}
return a;
return a;
}</lang>
}</syntaxhighlight>


====Memoization====
====Memoization====
Line 4,873: Line 7,853:
With the keys of a dictionary,
With the keys of a dictionary,


<lang javascript>var fib = (function(cache){
<syntaxhighlight lang="javascript">var fib = (function(cache){
return cache = cache || {}, function(n){
return cache = cache || {}, function(n){
if (cache[n]) return cache[n];
if (cache[n]) return cache[n];
Line 4,880: Line 7,860:
};
};
})();
})();
</syntaxhighlight>
</lang>


with the indices of an array,
with the indices of an array,


<lang javascript>(function () {
<syntaxhighlight lang="javascript">(function () {
'use strict';
'use strict';


Line 4,900: Line 7,880:
return fib(32);
return fib(32);


})();</lang>
})();</syntaxhighlight>




Line 4,908: Line 7,888:


====Y-Combinator====
====Y-Combinator====
<lang javascript>function Y(dn) {
<syntaxhighlight lang="javascript">function Y(dn) {
return (function(fn) {
return (function(fn) {
return fn(fn);
return fn(fn);
Line 4,924: Line 7,904:
return fn(n - 1) + fn(n - 2);
return fn(n - 1) + fn(n - 2);
};
};
});</lang>
});</syntaxhighlight>


====Generators====
====Generators====
<lang javascript>function* fibonacciGenerator() {
<syntaxhighlight lang="javascript">function* fibonacciGenerator() {
var prev = 0;
var prev = 0;
var curr = 1;
var curr = 1;
Line 4,936: Line 7,916:
}
}
}
}
var fib = fibonacciGenerator();</lang>
var fib = fibonacciGenerator();</syntaxhighlight>


===ES6===
===ES6===
Line 4,945: Line 7,925:
we can use an accumulating fold.
we can use an accumulating fold.


<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {
'use strict';
'use strict';


Line 4,979: Line 7,959:


// --> 2178309
// --> 2178309
})();</lang>
})();</syntaxhighlight>


Otherwise, a simple fold will suffice.
Otherwise, a simple fold will suffice.
Line 4,985: Line 7,965:
{{Trans|Haskell}} (Memoized fold example)
{{Trans|Haskell}} (Memoized fold example)


<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {
'use strict';
'use strict';


Line 5,006: Line 7,986:


// --> 2178309
// --> 2178309
})();</lang>
})();</syntaxhighlight>


{{Out}}
{{Out}}
Line 5,013: Line 7,993:
=={{header|Joy}}==
=={{header|Joy}}==
===Recursive===
===Recursive===
<lang joy>DEFINE fib == [small] [] [pred dup pred] [+] binrec.</lang>
<syntaxhighlight lang="joy">DEFINE fib == [small] [] [pred dup pred] [+] binrec.</syntaxhighlight>


===Iterative===
===Iterative===
<lang joy>DEFINE fib == [1 0] dip [swap [+] unary] times popd.</lang>
<syntaxhighlight lang="joy">DEFINE fib == [1 0] dip [swap [+] unary] times popd.</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
{{works with|jq}}
jq does not (yet) have infinite-precision integer arithmetic, and
'''Works with gojq, the Go implementation of jq'''
currently the following algorithms only give exact answers up to fib(78). At a certain point, integers are converted to floats,

The C implementation of jq does not (yet) have infinite-precision integer arithmetic, and
so using it, the following algorithms only give exact answers up to fib(78). By contrast,
using the Go implementation of jq and the definition of nth_fib given below:
<syntaxhighlight lang="jq">
nth_fib(pow(2;20)) | tostring | [length, .[:10], .[-10:]]
</syntaxhighlight>
yields
<pre>
[219140,"1186800606","0691163707"]
</pre>
in about 20 seconds on a 3GHz machine.

Using either the C or Go implementations, at a certain point, integers are converted to floats,
but floating point precision for fib(n) fails after n = 1476:
but floating point precision for fib(n) fails after n = 1476:
in jq, fib(1476) evaluates to 1.3069892237633987e+308
in jq, fib(1476) evaluates to 1.3069892237633987e+308


===Recursive===
===Recursive===
<lang jq>def nth_fib_naive(n):
<syntaxhighlight lang="jq">def nth_fib_naive(n):
if (n < 2) then n
if (n < 2) then n
else nth_fib_naive(n - 1) + nth_fib_naive(n - 2)
else nth_fib_naive(n - 1) + nth_fib_naive(n - 2)
end;</lang>
end;</syntaxhighlight>
===Tail Recursive===
===Tail Recursive===
Recent versions of jq (after July 1, 2014) include basic optimizations for tail recursion, and nth_fib is defined here to take advantage of TCO. For example, nth_fib(10000000) completes with only 380KB (that's K) of memory. However nth_fib can also be used with earlier versions of jq.
Recent versions of jq (after July 1, 2014) include basic optimizations for tail recursion, and nth_fib is defined here to take advantage of TCO. For example, nth_fib(10000000) completes with only 380KB (that's K) of memory. However nth_fib can also be used with earlier versions of jq.
<lang jq>def nth_fib(n):
<syntaxhighlight lang="jq">def nth_fib(n):
# input: [f(i-2), f(i-1), countdown]
# input: [f(i-2), f(i-1), countdown]
def fib: (.[0] + .[1]) as $sum
def fib: (.[0] + .[1]) as $sum
Line 5,039: Line 8,033:
| fib end;
| fib end;
[-1, 1, n] | fib;
[-1, 1, n] | fib;
</syntaxhighlight>
</lang>


Example:<lang jq>
Example:<syntaxhighlight lang="jq">
(range(0;5), 50) | [., nth_fib(.)]
(range(0;5), 50) | [., nth_fib(.)]
</syntaxhighlight>
</lang>
yields: <lang jq>[0,0]
yields: <syntaxhighlight lang="jq">[0,0]
[1,1]
[1,1]
[2,1]
[2,1]
[3,2]
[3,2]
[4,3]
[4,3]
[50,12586269025]</lang>
[50,12586269025]</syntaxhighlight>


===Binet's Formula===
===Binet's Formula===
<lang jq>def fib_binet(n):
<syntaxhighlight lang="jq">def fib_binet(n):
(5|sqrt) as $rt
(5|sqrt) as $rt
| ((1 + $rt)/2) as $phi
| ((1 + $rt)/2) as $phi
Line 5,058: Line 8,052:
| (if 0 == (n % 2) then 1 else -1 end) as $sign
| (if 0 == (n % 2) then 1 else -1 end) as $sign
| ( ($phin - ($sign / $phin) ) / $rt ) + .5
| ( ($phin - ($sign / $phin) ) / $rt ) + .5
| floor;</lang>
| floor;</syntaxhighlight>


===Generator===
===Generator===
The following is a jq generator which produces the first n terms of the Fibonacci sequence efficiently, one by one. Notice that it is simply a variant of the above tail-recursive function. The function is in effect turned into a generator by changing "( _ | fib )" to "$sum, (_ | fib)".<lang jq># Generator
The following is a jq generator which produces the first n terms of the Fibonacci sequence efficiently, one by one. Notice that it is simply a variant of the above tail-recursive function. The function is in effect turned into a generator by changing "( _ | fib )" to "$sum, (_ | fib)".<syntaxhighlight lang="jq"># Generator
def fibonacci(n):
def fibonacci(n):
# input: [f(i-2), f(i-1), countdown]
# input: [f(i-2), f(i-1), countdown]
Line 5,068: Line 8,062:
else $sum, ([ .[1], $sum, .[2] - 1 ] | fib)
else $sum, ([ .[1], $sum, .[2] - 1 ] | fib)
end;
end;
[-1, 1, n] | fib;</lang>
[-1, 1, n] | fib;</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
===Recursive===
===Recursive===
<lang Julia>fib(n) = n < 2 ? n : fib(n-1) + fib(n-2)</lang>
<syntaxhighlight lang="julia">fib(n) = n < 2 ? n : fib(n-1) + fib(n-2)</syntaxhighlight>
===Iterative===
===Iterative===
<lang Julia>function fib(n)
<syntaxhighlight lang="julia">function fib(n)
x,y = (0,1)
x,y = (0,1)
for i = 1:n x,y = (y, x+y) end
for i = 1:n x,y = (y, x+y) end
x
x
end</lang>
end</syntaxhighlight>
===Matrix form===
===Matrix form===
<lang Julia>fib(n) = ([1 1 ; 1 0]^n)[1,2]</lang>
<syntaxhighlight lang="julia">fib(n) = ([1 1 ; 1 0]^n)[1,2]</syntaxhighlight>


=={{header|K}}==
=={{header|K}}==
{{works with|Kona}}


===Recursive===
===Recursive===
<lang K>{:[x<3;1;_f[x-1]+_f[x-2]]}</lang>
<syntaxhighlight lang="k">{:[x<3;1;_f[x-1]+_f[x-2]]}</syntaxhighlight>


===Recursive with memoization===
===Recursive with memoization===
Using a (global) dictionary c.
Using a (global) dictionary c.


<lang K>{c::.();{v:c[a:`$$x];:[x<3;1;:[_n~v;c[a]:_f[x-1]+_f[x-2];v]]}x}</lang>
<syntaxhighlight lang="k">{c::.();{v:c[a:`$$x];:[x<3;1;:[_n~v;c[a]:_f[x-1]+_f[x-2];v]]}x}</syntaxhighlight>


===Analytic===
===Analytic===
<lang K>phi:(1+_sqrt(5))%2
<syntaxhighlight lang="k">phi:(1+_sqrt(5))%2
{_((phi^x)-((1-phi)^x))%_sqrt[5]}</lang>
{_((phi^x)-((1-phi)^x))%_sqrt[5]}</syntaxhighlight>


===Sequence to n===
===Sequence to n===
{{works with|Kona}} {{works with|ngn/k}}
<lang K>{(x(|+\)\1 1)[;1]}</lang>
<lang K>{x{x,+/-2#x}/!2}</lang>
<syntaxhighlight lang="k">{(x(|+\)\1 1)[;1]}</syntaxhighlight>
<syntaxhighlight lang="k">{x{x,+/-2#x}/!2}</syntaxhighlight>

=={{header|Julia}}==
===Recursive===
<lang Julia>fib(n) = n < 2 ? n : fib(n-1) + fib(n-2)</lang>
===Iterative===
<lang Julia>function fib(n)
x,y = (0,1)
for i = 1:n x,y = (y, x+y) end
x
end</lang>
===Matrix form===
<lang Julia>fib(n) = ([1 1 ; 1 0]^n)[1,2]</lang>


=={{header|Kabap}}==
=={{header|Kabap}}==


===Sequence to n===
===Sequence to n===
<syntaxhighlight lang="kabap">
<lang Kabap>
// Calculate the $n'th Fibonacci number
// Calculate the $n'th Fibonacci number


Line 5,151: Line 8,135:
// Return the sequence
// Return the sequence
return = "Fibonacci number " << $i << " is " << $a << " (" << $sequence << ")";
return = "Fibonacci number " << $i << " is " << $a << " (" << $sequence << ")";
</syntaxhighlight>
</lang>

=={{header|Klingphix}}==
<syntaxhighlight lang="text">:Fibonacci
dup 0 less
( ["Invalid argument"]
[1 1 rot 2 sub [drop over over add] for]
) if
;

30 Fibonacci pstack print nl

msec print nl
"bertlham " input</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>enum class Fibonacci {
<syntaxhighlight lang="kotlin">enum class Fibonacci {
ITERATIVE {
ITERATIVE {
override fun invoke(n: Long) = if (n < 2) {
override fun get(n: Int): Long = if (n < 2) {
n
n.toLong()
} else {
} else {
var n1 = 0L
var n1 = 0L
var n2 = 1L
var n2 = 1L
var i = n
repeat(n) {
do {
val sum = n1 + n2
val sum = n1 + n2
n1 = n2
n1 = n2
n2 = sum
n2 = sum
} while (i-- > 1)
}
n1
n1
}
}
},
},
RECURSIVE {
RECURSIVE {
override fun invoke(n: Long): Long = if (n < 2) n else this(n - 1) + this(n - 2)
override fun get(n: Int): Long = if (n < 2) n.toLong() else this[n - 1] + this[n - 2]
};
},
CACHING {

val cache: MutableMap<Int, Long> = mutableMapOf(0 to 0L, 1 to 1L)
abstract operator fun invoke(n: Long): Long
override fun get(n: Int): Long = if (n < 2) n.toLong() else impl(n)
private fun impl(n: Int): Long = cache.computeIfAbsent(n) { impl(it-1) + impl(it-2) }
},
;
abstract operator fun get(n: Int): Long
}
}

fun main(a: Array<String>) {
fun main() {
val r = 0..30L
val r = 0..30
Fibonacci.values().forEach {
for (fib in Fibonacci.values()) {
print("${it.name}: ")
print("${fib.name.padEnd(10)}:")
r.forEach { i -> print(" " + it(i)) }
for (i in r) { print(" " + fib[i]) }
println()
println()
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>ITERATIVE: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040
<pre>ITERATIVE: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040
RECURSIVE: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040</pre>
RECURSIVE: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040
CACHING : 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040
</pre>


=={{header|L++}}==
=={{header|L++}}==
<lang lisp>(defn int fib (int n) (return (? (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))))
<syntaxhighlight lang="lisp">(defn int fib (int n) (return (? (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))))
(main (prn (fib 30)))</lang>
(main (prn (fib 30)))</syntaxhighlight>


=={{header|LabVIEW}}==
=={{header|LabVIEW}}==
{{VI solution|LabVIEW_Fibonacci_sequence.png}}
{{VI solution|LabVIEW_Fibonacci_sequence.png}}


=={{header|Lang5}}==
=={{header|Lambdatalk}}==
<lang lang5>[] '__A set : dip swap __A swap 2 compress collapse '__A set execute
__A -1 extract nip ; : nip swap drop ; : tuck swap over ;
: -rot rot rot ; : 0= 0 == ; : 1+ 1 + ; : 1- 1 - ; : sum '+ reduce ;
: bi 'keep dip execute ; : keep over 'execute dip ;

: fib dup 1 > if dup 1- fib swap 2 - fib + then ;
: fib dup 1 > if "1- fib" "2 - fib" bi + then ;</lang>


=={{header|lambdatalk}}==


<lang scheme>
<syntaxhighlight lang="scheme">
1) basic version
1) basic version
{def fib1
{def fib1
Line 5,292: Line 8,286:
{fib5 1000} -> 4.346655768693743e+208 (CPU ~ 1ms)
{fib5 1000} -> 4.346655768693743e+208 (CPU ~ 1ms)


</syntaxhighlight>
</lang>

=={{header|Lang}}==
===Iterative===
<syntaxhighlight lang="lang">
fp.fib = ($n) -> {
if($n < 2) {
return $n
}
$prev = 1
$cur = 1
$i = 2
while($i < $n) {
$tmp = $cur
$cur += $prev
$prev = $tmp
$i += 1
}
return $cur
}
</syntaxhighlight>

===Recursive===
<syntaxhighlight lang="lang">
fp.fib = ($n) -> {
if($n < 2) {
return $n
}
return parser.op(fp.fib($n - 1) + fp.fib($n - 2))
}
</syntaxhighlight>

=={{header|Lang5}}==
<syntaxhighlight lang="lang5">[] '__A set : dip swap __A swap 2 compress collapse '__A set execute
__A -1 extract nip ; : nip swap drop ; : tuck swap over ;
: -rot rot rot ; : 0= 0 == ; : 1+ 1 + ; : 1- 1 - ; : sum '+ reduce ;
: bi 'keep dip execute ; : keep over 'execute dip ;

: fib dup 1 > if dup 1- fib swap 2 - fib + then ;
: fib dup 1 > if "1- fib" "2 - fib" bi + then ;</syntaxhighlight>

=={{header|langur}}==
<syntaxhighlight lang="langur">val .fibonacci = fn(.x) { if(.x < 2: .x ; self(.x - 1) + self(.x - 2)) }

writeln map .fibonacci, series 2..20</syntaxhighlight>

{{out}}
<pre>[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]</pre>


=={{header|Lasso}}==
=={{header|Lasso}}==
<syntaxhighlight lang="lasso">
<lang Lasso>
define fibonacci(n::integer) => {
define fibonacci(n::integer) => {


Line 5,319: Line 8,364:
fibonacci(2) //->output 1
fibonacci(2) //->output 1
fibonacci(3) //->output 2
fibonacci(3) //->output 2
</syntaxhighlight>
</lang>

=={{header|Latitude}}==

===Recursive===
<syntaxhighlight lang="latitude">fibo := {
takes '[n].
if { n <= 1. } then {
n.
} else {
fibo (n - 1) + fibo (n - 2).
}.
}.</syntaxhighlight>

===Memoization===
<syntaxhighlight lang="latitude">fibo := {
takes '[n].
cache := here cache.
{ cache slot? (n ordinal). } ifFalse {
cache slot (n ordinal) =
if { n <= 1. } then {
n.
} else {
fibo (n - 1) + fibo (n - 2).
}.
}.
cache slot (n ordinal).
} tap {
;; Attach the cache to the method object itself.
#'self cache := Object clone.
}.</syntaxhighlight>


=={{header|Lean}}==

It runs on Lean 3.4.2:

<syntaxhighlight lang="lean">
-- Our first implementation is the usual recursive definition:
def fib1 : ℕ → ℕ
| 0 := 0
| 1 := 1
| (n + 2) := fib1 n + fib1 (n + 1)


-- We can give a second more efficient implementation using an auxiliary function:
def fib_aux : ℕ → ℕ → ℕ → ℕ
| 0 a b := b
| (n + 1) a b := fib_aux n (a + b) a

def fib2 : ℕ → ℕ
| n := fib_aux n 1 0


-- Use #eval to check computations:
#eval fib1 20
#eval fib2 20</syntaxhighlight>


It runs on Lean 4:

<syntaxhighlight lang="lean">
-- Naive version
def fib1 (n : Nat) : Nat :=
match n with
| 0 => 0
| 1 => 1
| (k + 2) => fib1 k + fib1 (k + 1)

-- More efficient version
def fib_aux (n : Nat) (a : Nat) (b : Nat) : Nat :=
match n with
| 0 => b
| (k + 1) => fib_aux k (a + b) a
def fib2 (n : Nat) : Nat :=
fib_aux n 1 0

-- Examples
#eval fib1 20
#eval fib2 20
</syntaxhighlight>


=={{header|LFE}}==
=={{header|LFE}}==
Line 5,325: Line 8,451:
===Recursive===
===Recursive===


<lang lisp>
<syntaxhighlight lang="lisp">
(defun fib
(defun fib
((0) 0)
((0) 0)
Line 5,332: Line 8,458:
(+ (fib (- n 1))
(+ (fib (- n 1))
(fib (- n 2)))))
(fib (- n 2)))))
</syntaxhighlight>
</lang>


===Iterative===
===Iterative===


<lang lisp>
<syntaxhighlight lang="lisp">
(defun fib
(defun fib
((n) (when (>= n 0))
((n) (when (>= n 0))
Line 5,347: Line 8,473:
(fib (- n 1) next (+ result next))))
(fib (- n 1) next (+ result next))))


</syntaxhighlight>
</lang>


=={{header|Liberty BASIC}}==
===Iterative/Recursive===
<lang lb>
for i = 0 to 15
print fiboR(i),fiboI(i)
next i
function fiboR(n)
if n <= 1 then
fiboR = n
else
fiboR = fiboR(n-1) + fiboR(n-2)
end if
end function
function fiboI(n)
a = 0
b = 1
for i = 1 to n
temp = a + b
a = b
b = temp
next i
fiboI = a
end function
</lang>
{{out}}
<pre>
0 0
1 1
1 1
2 2
3 3
5 5
8 8
13 13
21 21
34 34
55 55
89 89
144 144
233 233
377 377
610 610
</pre>
===Iterative/Negative===
<lang lb>
print "Rosetta Code - Fibonacci sequence": print
print " n Fn"
for x=-12 to 12 '68 max
print using("### ", x); using("##############", FibonacciTerm(x))
next x
print
[start]
input "Enter a term#: "; n$
n$=lower$(trim$(n$))
if n$="" then print "Program complete.": end
print FibonacciTerm(val(n$))
goto [start]

function FibonacciTerm(n)
n=int(n)
FTa=0: FTb=1: FTc=-1
select case
case n=0 : FibonacciTerm=0 : exit function
case n=1 : FibonacciTerm=1 : exit function
case n=-1 : FibonacciTerm=-1 : exit function
case n>1
for x=2 to n
FibonacciTerm=FTa+FTb
FTa=FTb: FTb=FibonacciTerm
next x
exit function
case n<-1
for x=-2 to n step -1
FibonacciTerm=FTa+FTc
FTa=FTc: FTc=FibonacciTerm
next x
exit function
end select
end function
</lang>
{{out}}
<pre>
Rosetta Code - Fibonacci sequence

n Fn
-12 -144
-11 -89
-10 -55
-9 -34
-8 -21
-7 -13
-6 -8
-5 -5
-4 -3
-3 -2
-2 -1
-1 -1
0 0
1 1
2 1
3 2
4 3
5 5
6 8
7 13
8 21
9 34
10 55
11 89
12 144

Enter a term#: 12
144
Enter a term#:
Program complete.
</pre>


=={{header|Lingo}}==
=={{header|Lingo}}==

===Recursive===
===Recursive===
<syntaxhighlight lang="lingo">on fib (n)

<lang lingo>on fib (n)
if n<2 then return n
if n<2 then return n
return fib(n-1)+fib(n-2)
return fib(n-1)+fib(n-2)
end</lang>
end</syntaxhighlight>


===Iterative===
===Iterative===
<syntaxhighlight lang="lingo">on fib (n)

<lang lingo>on fib (n)
if n<2 then return n
if n<2 then return n
fibPrev = 0
fibPrev = 0
Line 5,489: Line 8,494:
end repeat
end repeat
return fib
return fib
end</lang>
end</syntaxhighlight>


===Analytic===
===Analytic===
<syntaxhighlight lang="lingo">on fib (n)

<lang lingo>on fib (n)
sqrt5 = sqrt(5.0)
sqrt5 = sqrt(5.0)
p = (1+sqrt5)/2
p = (1+sqrt5)/2
q = 1 - p
q = 1 - p
return integer((power(p,n)-power(q,n))/sqrt5)
return integer((power(p,n)-power(q,n))/sqrt5)
end</lang>
end</syntaxhighlight>


=={{header|Lisaac}}==
=={{header|Lisaac}}==
<lang Lisaac>- fib(n : UINTEGER_32) : UINTEGER_64 <- (
<syntaxhighlight lang="lisaac">- fib(n : UINTEGER_32) : UINTEGER_64 <- (
+ result : UINTEGER_64;
+ result : UINTEGER_64;
(n < 2).if {
(n < 2).if {
Line 5,509: Line 8,513:
};
};
result
result
);</lang>
);</syntaxhighlight>


=={{header|LiveCode}}==
=={{header|LiveCode}}==
<lang LiveCode>-- Iterative, translation of the basic version.
<syntaxhighlight lang="livecode">-- Iterative, translation of the basic version.
function fibi n
function fibi n
put 0 into aa
put 0 into aa
Line 5,531: Line 8,535:
return fibr(n-1) + fibr(n-2)
return fibr(n-1) + fibr(n-2)
end if
end if
end fibr</lang>
end fibr</syntaxhighlight>

=={{header|LLVM}}==
<syntaxhighlight lang="llvm">; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.

; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps

$"PRINT_LONG" = comdat any
@"PRINT_LONG" = linkonce_odr unnamed_addr constant [5 x i8] c"%ld\0A\00", comdat, align 1

;--- The declaration for the external C printf function.
declare i32 @printf(i8*, ...)

;--------------------------------------------------------------------
;-- Function for calculating the nth fibonacci numbers
;--------------------------------------------------------------------
define i32 @fibonacci(i32) {
%2 = alloca i32, align 4 ;-- allocate local copy of n
%3 = alloca i32, align 4 ;-- allocate a
%4 = alloca i32, align 4 ;-- allocate b
store i32 %0, i32* %2, align 4 ;-- store copy of n
store i32 0, i32* %3, align 4 ;-- a := 0
store i32 1, i32* %4, align 4 ;-- b := 1
br label %loop

loop:
%5 = load i32, i32* %2, align 4 ;-- load n
%6 = icmp sgt i32 %5, 0 ;-- n > 0
br i1 %6, label %loop_body, label %exit

loop_body:
%7 = load i32, i32* %3, align 4 ;-- load a
%8 = load i32, i32* %4, align 4 ;-- load b
%9 = add nsw i32 %7, %8 ;-- t = a + b
store i32 %8, i32* %3, align 4 ;-- store a = b
store i32 %9, i32* %4, align 4 ;-- store b = t
%10 = load i32, i32* %2, align 4 ;-- load n
%11 = add nsw i32 %10, -1 ;-- decrement n
store i32 %11, i32* %2, align 4 ;-- store n
br label %loop

exit:
%12 = load i32, i32* %3, align 4 ;-- load a
ret i32 %12 ;-- return a
}

;--------------------------------------------------------------------
;-- Main function for printing successive fibonacci numbers
;--------------------------------------------------------------------
define i32 @main() {
%1 = alloca i32, align 4 ;-- allocate index
store i32 0, i32* %1, align 4 ;-- index := 0
br label %loop

loop:
%2 = load i32, i32* %1, align 4 ;-- load index
%3 = icmp sle i32 %2, 12 ;-- index <= 12
br i1 %3, label %loop_body, label %exit

loop_body:
%4 = load i32, i32* %1, align 4 ;-- load index
%5 = call i32 @fibonacci(i32 %4)
%6 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"PRINT_LONG", i32 0, i32 0), i32 %5)
%7 = load i32, i32* %1, align 4 ;-- load index
%8 = add nsw i32 %7, 1 ;-- increment index
store i32 %8, i32* %1, align 4 ;-- store index
br label %loop

exit:
ret i32 0 ;-- return EXIT_SUCCESS
}</syntaxhighlight>
{{out}}
<pre>0
1
1
2
3
5
8
13
21
34
55
89
144</pre>


=={{header|Logo}}==
=={{header|Logo}}==
<syntaxhighlight lang="logo">
<lang logo>to fib :n [:a 0] [:b 1]
to fib "loop
if :n < 1 [output :a]
make "fib1 0
output (fib :n-1 :b :a+:b)
make "fib2 1
end</lang>

type [You requested\ ]
type :loop
print [\ Fibonacci Numbers]
type :fib1
type [\ ]
type :fib2
type [\ ]
make "loop :loop - 2
repeat :loop [ make "fibnew :fib1 + :fib2 type :fibnew type [\ ] make "fib1 :fib2 make "fib2 :fibnew ]
print [\ ]
end
</syntaxhighlight>


=={{header|LOLCODE}}==
=={{header|LOLCODE}}==
<syntaxhighlight lang="lolcode">
<lang LOLCODE>
HAI 1.2
HAI 1.2
HOW DUZ I fibonacci YR N
HOW DUZ I fibonacci YR N
Line 5,557: Line 8,662:
IF U SAY SO
IF U SAY SO
KTHXBYE
KTHXBYE
</syntaxhighlight>
</lang>

=={{header|Lua}}==
<lang lua>--calculates the nth fibonacci number. Breaks for negative or non-integer n.
function fibs(n)
return n < 2 and n or fibs(n - 1) + fibs(n - 2)
end

--more pedantic version, returns 0 for non-integer n
function pfibs(n)
if n ~= math.floor(n) then return 0
elseif n < 0 then return pfibs(n + 2) - pfibs(n + 1)
elseif n < 2 then return n
else return pfibs(n - 1) + pfibs(n - 2)
end
end

--tail-recursive
function a(n,u,s) if n<2 then return u+s end return a(n-1,u+s,u) end
function trfib(i) return a(i-1,1,0) end

--table-recursive
fib_n = setmetatable({1, 1}, {__index = function(z,n) return n<=0 and 0 or z[n-1] + z[n-2] end})

--table-recursive done properly (values are actually saved into table; also the first element
-- of Fibonacci sequence is 0, so the initial table should be {0, 1}).
fib_n = setmetatable({0, 1}, {
__index = function(t,n)
if n <= 0 then return 0 end
t[n] = t[n-1] + t[n-2]
return t[n]
end
})

--loop version
function lfibs(n)
local p0,p1=0,1
for _=1,n do p0,p1 = p1,p0+p1 end
return p0
end</lang>

=={{header|Luck}}==
<lang luck>function fib(x: int): int = (
let cache = {} in
let fibc x = if x<=1 then x else (
if x not in cache then
cache[x] = fibc(x-1) + fibc(x-2);
cache[x]
) in fibc(x)
);;
for x in range(10) do print(fib(x))</lang>

=={{header|Lush}}==
<lang lush>(de fib-rec (n)
(if (< n 2)
n
(+ (fib-rec (- n 2)) (fib-rec (- n 1)))))</lang>


=={{header|LSL}}==
=={{header|LSL}}==
Rez a box on the ground, and add the following as a New Script.
Rez a box on the ground, and add the following as a New Script.
<lang LSL>integer Fibonacci(integer n) {
<syntaxhighlight lang="lsl">integer Fibonacci(integer n) {
if(n<2) {
if(n<2) {
return n;
return n;
Line 5,631: Line 8,680:
}
}
}
}
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 5,670: Line 8,719:
Fibonacci(34)=5702887
Fibonacci(34)=5702887
</pre>
</pre>

=={{header|Lua}}==
===Recursive===
<syntaxhighlight lang="lua">
--calculates the nth fibonacci number. Breaks for negative or non-integer n.
function fibs(n)
return n < 2 and n or fibs(n - 1) + fibs(n - 2)
end
</syntaxhighlight>

===Pedantic Recursive===
<syntaxhighlight lang="lua">
--more pedantic version, returns 0 for non-integer n
function pfibs(n)
if n ~= math.floor(n) then return 0
elseif n < 0 then return pfibs(n + 2) - pfibs(n + 1)
elseif n < 2 then return n
else return pfibs(n - 1) + pfibs(n - 2)
end
end
</syntaxhighlight>

===Tail Recursive===
<syntaxhighlight lang="lua">
function a(n,u,s) if n<2 then return u+s end return a(n-1,u+s,u) end
function trfib(i) return a(i-1,1,0) end
</syntaxhighlight>

===Table Recursive===
<syntaxhighlight lang="lua">
fib_n = setmetatable({1, 1}, {__index = function(z,n) return n<=0 and 0 or z[n-1] + z[n-2] end})
</syntaxhighlight>

===Table Recursive 2===
<syntaxhighlight lang="lua">
-- table recursive done properly (values are actually saved into table;
-- also the first element of Fibonacci sequence is 0, so the initial table should be {0, 1}).
fib_n = setmetatable({0, 1}, {
__index = function(t,n)
if n <= 0 then return 0 end
t[n] = t[n-1] + t[n-2]
return t[n]
end
})
</syntaxhighlight>

===Iterative===
<syntaxhighlight lang="lua">
function ifibs(n)
local p0,p1=0,1
for _=1,n do p0,p1 = p1,p0+p1 end
return p0
end
</syntaxhighlight>

=={{header|Luck}}==
<syntaxhighlight lang="luck">function fib(x: int): int = (
let cache = {} in
let fibc x = if x<=1 then x else (
if x not in cache then
cache[x] = fibc(x-1) + fibc(x-2);
cache[x]
) in fibc(x)
);;
for x in range(10) do print(fib(x))</syntaxhighlight>

=={{header|Lush}}==
<syntaxhighlight lang="lush">(de fib-rec (n)
(if (< n 2)
n
(+ (fib-rec (- n 2)) (fib-rec (- n 1)))))</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
Return decimal type and use an Inventory (as closure) to store known return values. All closures are in scope in every recursive call (we use here lambda(), but we can use fib(), If we make Fib1=fib then we have to use lambda() for recursion.
Return decimal type and use an Inventory (as closure) to store known return values. All closures are in scope in every recursive call (we use here lambda(), but we can use fib(), If we make Fib1=fib then we have to use lambda() for recursion.
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Inventory K=0:=0,1:=1
Inventory K=0:=0,1:=1
fib=Lambda K (x as decimal)-> {
fib=Lambda K (x as decimal)-> {
Line 5,686: Line 8,806:
Print Fib(i)
Print Fib(i)
}
}
</syntaxhighlight>
</lang>


Here an example where we use a BigNum class to make a Group which hold a stack of values, and take 14 digits per item in stack. We can use inventory to hold groups, so we use the fast fib() function from code above, where we remove the type definition of Ret variable, and set two first items in inventory as groups.
Here an example where we use a BigNum class to make a Group which hold a stack of values, and take 14 digits per item in stack. We can use inventory to hold groups, so we use the fast fib() function from code above, where we remove the type definition of Ret variable, and set two first items in inventory as groups.


<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>


Class BigNum {
Class BigNum {
Line 5,771: Line 8,891:




</syntaxhighlight>
</lang>


=={{header|M4}}==
=={{header|M4}}==
<lang m4>define(`fibo',`ifelse(0,$1,0,`ifelse(1,$1,1,
<syntaxhighlight lang="m4">define(`fibo',`ifelse(0,$1,0,`ifelse(1,$1,1,
`eval(fibo(decr($1)) + fibo(decr(decr($1))))')')')dnl
`eval(fibo(decr($1)) + fibo(decr(decr($1))))')')')dnl
define(`loop',`ifelse($1,$2,,`$3($1) loop(incr($1),$2,`$3')')')dnl
define(`loop',`ifelse($1,$2,,`$3($1) loop(incr($1),$2,`$3')')')dnl
loop(0,15,`fibo')</lang>
loop(0,15,`fibo')</syntaxhighlight>

=={{header|MAD}}==

<syntaxhighlight lang="mad"> NORMAL MODE IS INTEGER
INTERNAL FUNCTION(N)
ENTRY TO FIB.
A = 0
B = 1
THROUGH LOOP, FOR N=N, -1, N.E.0
C = A + B
A = B
LOOP B = C
FUNCTION RETURN A
END OF FUNCTION
THROUGH SHOW, FOR I=0, 1, I.GE.20
SHOW PRINT FORMAT FNUM, I, FIB.(I)
VECTOR VALUES FNUM = $4HFIB(,I2,4H) = ,I4*$
END OF PROGRAM </syntaxhighlight>

{{out}}

<pre style='height: 50ex;'>FIB( 0) = 0
FIB( 1) = 1
FIB( 2) = 1
FIB( 3) = 2
FIB( 4) = 3
FIB( 5) = 5
FIB( 6) = 8
FIB( 7) = 13
FIB( 8) = 21
FIB( 9) = 34
FIB(10) = 55
FIB(11) = 89
FIB(12) = 144
FIB(13) = 233
FIB(14) = 377
FIB(15) = 610
FIB(16) = 987
FIB(17) = 1597
FIB(18) = 2584
FIB(19) = 4181</pre>



=={{header|Maple}}==
=={{header|Maple}}==
<lang maple>
<syntaxhighlight lang="maple">
> f := n -> ifelse(n<3,1,f(n-1)+f(n-2));
> f := n -> ifelse(n<3,1,f(n-1)+f(n-2));
> f(2);
> f(2);
Line 5,786: Line 8,950:
> f(3);
> f(3);
2
2
</syntaxhighlight>
</lang>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
The Wolfram Language already has a built-in function <tt>Fibonacci</tt>, but a simple recursive implementation would be
The Wolfram Language already has a built-in function <tt>Fibonacci</tt>, but a simple recursive implementation would be


<lang mathematica>fib[0] = 0
<syntaxhighlight lang="mathematica">fib[0] = 0
fib[1] = 1
fib[1] = 1
fib[n_Integer] := fib[n - 1] + fib[n - 2]</lang>
fib[n_Integer] := fib[n - 1] + fib[n - 2]</syntaxhighlight>


An optimization is to cache the values already calculated:
An optimization is to cache the values already calculated:


<lang mathematica>fib[0] = 0
<syntaxhighlight lang="mathematica">fib[0] = 0
fib[1] = 1
fib[1] = 1
fib[n_Integer] := fib[n] = fib[n - 1] + fib[n - 2]</lang>
fib[n_Integer] := fib[n] = fib[n - 1] + fib[n - 2]</syntaxhighlight>


The above implementations may be too simplistic, as the first is incredibly slow for any reasonable range due to nested recursions and while the second is faster it uses an increasing amount of memory. The following uses recursion much more effectively while not using memory:
The above implementations may be too simplistic, as the first is incredibly slow for any reasonable range due to nested recursions and while the second is faster it uses an increasing amount of memory. The following uses recursion much more effectively while not using memory:


<lang mathematica>fibi[prvprv_Integer, prv_Integer, rm_Integer] :=
<syntaxhighlight lang="mathematica">fibi[prvprv_Integer, prv_Integer, rm_Integer] :=
If[rm < 1, prvprv, fibi[prv, prvprv + prv, rm - 1]]
If[rm < 1, prvprv, fibi[prv, prvprv + prv, rm - 1]]
fib[n_Integer] := fibi[0, 1, n]</lang>
fib[n_Integer] := fibi[0, 1, n]</syntaxhighlight>


However, the recursive approaches in Mathematica are limited by the limit set for recursion depth (default 1024 or 4096 for the above cases), limiting the range for 'n' to about 1000 or 2000. The following using an iterative approach has an extremely high limit (greater than a million):
However, the recursive approaches in Mathematica are limited by the limit set for recursion depth (default 1024 or 4096 for the above cases), limiting the range for 'n' to about 1000 or 2000. The following using an iterative approach has an extremely high limit (greater than a million):


<lang mathematica>fib[n_Integer] := Block[{tmp, prvprv = 0, prv = 1},
<syntaxhighlight lang="mathematica">fib[n_Integer] := Block[{tmp, prvprv = 0, prv = 1},
For[i = 0, i < n, i++, tmp = prv; prv += prvprv; prvprv = tmp];
For[i = 0, i < n, i++, tmp = prv; prv += prvprv; prvprv = tmp];
Return[prvprv]]</lang>
Return[prvprv]]</syntaxhighlight>


If one wanted a list of Fibonacci numbers, the following is quite efficient:
If one wanted a list of Fibonacci numbers, the following is quite efficient:


<lang mathematica>fibi[{prvprv_Integer, prv_Integer}] := {prv, prvprv + prv}
<syntaxhighlight lang="mathematica">fibi[{prvprv_Integer, prv_Integer}] := {prv, prvprv + prv}
fibList[n_Integer] := Map[Take[#, 1] &, NestList[fibi, {0, 1}, n]] // Flatten</lang>
fibList[n_Integer] := Map[Take[#, 1] &, NestList[fibi, {0, 1}, n]] // Flatten</syntaxhighlight>


Output from the last with "fibList[100]":
Output from the last with "fibList[100]":


<lang mathematica>{0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, \
<syntaxhighlight lang="mathematica">{0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, \
1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, \
1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, \
196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, \
196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, \
Line 5,840: Line 9,004:
19740274219868223167, 31940434634990099905, 51680708854858323072, \
19740274219868223167, 31940434634990099905, 51680708854858323072, \
83621143489848422977, 135301852344706746049, 218922995834555169026, \
83621143489848422977, 135301852344706746049, 218922995834555169026, \
354224848179261915075}</lang>
354224848179261915075}</syntaxhighlight>


The Wolfram Language can also solve recurrence equations using the built-in function <tt>RSolve</tt>
The Wolfram Language can also solve recurrence equations using the built-in function <tt>RSolve</tt>


<lang mathematica>fib[n] /. RSolve[{fib[n] == fib[n - 1] + fib[n - 2], fib[0] == 0,
<syntaxhighlight lang="mathematica">fib[n] /. RSolve[{fib[n] == fib[n - 1] + fib[n - 2], fib[0] == 0,
fib[1] == 1}, fib[n], n][[1]]</lang>
fib[1] == 1}, fib[n], n][[1]]</syntaxhighlight>


which evaluates to the built-in function <tt>Fibonacci[n]</tt>
which evaluates to the built-in function <tt>Fibonacci[n]</tt>
Line 5,851: Line 9,015:
This function can also be expressed as
This function can also be expressed as


<lang mathematica>Fibonacci[n] // FunctionExpand // FullSimplify</lang>
<syntaxhighlight lang="mathematica">Fibonacci[n] // FunctionExpand // FullSimplify</syntaxhighlight>


which evaluates to
which evaluates to


<lang mathematica>(2^-n ((1 + Sqrt[5])^n - (-1 + Sqrt[5])^n Cos[n π]))/Sqrt[5]</lang>
<syntaxhighlight lang="mathematica">(2^-n ((1 + Sqrt[5])^n - (-1 + Sqrt[5])^n Cos[n π]))/Sqrt[5]</syntaxhighlight>


and is defined for all real or complex values of n.
and is defined for all real or complex values of n.
Line 5,864: Line 9,028:
{{trans|Julia}}
{{trans|Julia}}


<lang MATLAB>function f = fib(n)
<syntaxhighlight lang="matlab">function f = fib(n)
f = [1 1 ; 1 0]^(n-1);
f = [1 1 ; 1 0]^(n-1);
f = f(1,1);
f = f(1,1);
end</lang>
end</syntaxhighlight>


===Iterative===
===Iterative===
<lang MATLAB>function F = fibonacci(n)
<syntaxhighlight lang="matlab">function F = fibonacci(n)
Fn = [1 0]; %Fn(1) is F_{n-2}, Fn(2) is F_{n-1}
Fn = [1 0]; %Fn(1) is F_{n-2}, Fn(2) is F_{n-1}
Line 5,887: Line 9,051:
end
end


end</lang>
end</syntaxhighlight>


===Dramadah Matrix Method===
===Dramadah Matrix Method===
The MATLAB help file suggests an interesting method of generating the Fibonacci numbers. Apparently the determinate of the Dramadah Matrix of type 3 (MATLAB designation) and size n-by-n is the nth Fibonacci number. This method is implimented below.
The MATLAB help file suggests an interesting method of generating the Fibonacci numbers. Apparently the determinate of the Dramadah Matrix of type 3 (MATLAB designation) and size n-by-n is the nth Fibonacci number. This method is implimented below.


<lang MATLAB>function number = fibonacci2(n)
<syntaxhighlight lang="matlab">function number = fibonacci2(n)
if n == 1
if n == 1
Line 5,904: Line 9,068:
end
end


end</lang>
end</syntaxhighlight>


===Tartaglia/Pascal Triangle Method===
===Tartaglia/Pascal Triangle Method===
<syntaxhighlight lang="matlab">
<lang Matlab>
function number = fibonacci(n)
function number = fibonacci(n)
%construct the Tartaglia/Pascal Triangle
%construct the Tartaglia/Pascal Triangle
Line 5,920: Line 9,084:
number=trace(rot90(pt));
number=trace(rot90(pt));
end
end
</syntaxhighlight>
</lang>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>/* fib(n) is built-in; here is an implementation */
<syntaxhighlight lang="maxima">/* fib(n) is built-in; here is an implementation */
fib2(n) := (matrix([0, 1], [1, 1])^^n)[1, 2]$
fib2(n) := (matrix([0, 1], [1, 1])^^n)[1, 2]$


Line 5,930: Line 9,094:


fib2(-10);
fib2(-10);
-55</lang>
-55</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
===Iterative===
===Iterative===
<lang maxscript>fn fibIter n =
<syntaxhighlight lang="maxscript">fn fibIter n =
(
(
if n < 2 then
if n < 2 then
Line 5,952: Line 9,116:
fib
fib
)
)
)</lang>
)</syntaxhighlight>
===Recursive===
===Recursive===
<lang maxscript>fn fibRec n =
<syntaxhighlight lang="maxscript">fn fibRec n =
(
(
if n < 2 then
if n < 2 then
Line 5,964: Line 9,128:
fibRec (n - 1) + fibRec (n - 2)
fibRec (n - 1) + fibRec (n - 2)
)
)
)</lang>
)</syntaxhighlight>


=={{header|Mercury}}==
=={{header|Mercury}}==
Line 5,972: Line 9,136:


===fib.m===
===fib.m===
<lang mercury>
<syntaxhighlight lang="mercury">
% The following code is derived from the Mercury Tutorial by Ralph Becket.
% The following code is derived from the Mercury Tutorial by Ralph Becket.
% http://www.mercury.csse.unimelb.edu.au/information/papers/book.pdf
% http://www.mercury.csse.unimelb.edu.au/information/papers/book.pdf
Line 6,002: Line 9,166:
write_int(fib(40), !IO),
write_int(fib(40), !IO),
write_string("\n", !IO).
write_string("\n", !IO).
</syntaxhighlight>
</lang>


=== Iterative algorithm ===
=== Iterative algorithm ===
Line 6,008: Line 9,172:
The much faster iterative algorithm can be written as:
The much faster iterative algorithm can be written as:


<lang mercury>
<syntaxhighlight lang="mercury">
:- pred fib_acc(int::in, int::in, int::in, int::in, int::out) is det.
:- pred fib_acc(int::in, int::in, int::in, int::in, int::out) is det.


Line 6,024: Line 9,188:
Res = Prev2 + Prev1
Res = Prev2 + Prev1
).
).
</syntaxhighlight>
</lang>


This predicate can be called as <lang mercury>fib_acc(1, 40, 1, 1, Result)</lang>
This predicate can be called as <syntaxhighlight lang="mercury">fib_acc(1, 40, 1, 1, Result)</syntaxhighlight>
It has several inputs which form the loop, the first is the current number, the second is a limit, ie when to stop counting. And the next two are accumulators for the last and next-to-last results.
It has several inputs which form the loop, the first is the current number, the second is a limit, ie when to stop counting. And the next two are accumulators for the last and next-to-last results.


Line 6,033: Line 9,197:
But what if you want the speed of the fib_acc with the recursive (more declarative) definition of fib? Then use memoization, because Mercury is a pure language fib(N, F) will always give the same F for the same N, guaranteed. Therefore memoization asks the compiler to use a table to remember the value for F for any N, and it's a one line change:
But what if you want the speed of the fib_acc with the recursive (more declarative) definition of fib? Then use memoization, because Mercury is a pure language fib(N, F) will always give the same F for the same N, guaranteed. Therefore memoization asks the compiler to use a table to remember the value for F for any N, and it's a one line change:


<lang mercury>
<syntaxhighlight lang="mercury">
:- pragma memo(fib/2).
:- pragma memo(fib/2).
:- pred fib(int::in, int::out) is det.
:- pred fib(int::in, int::out) is det.
Line 6,040: Line 9,204:
then X = 1
then X = 1
else fib(N - 1, A), fib(N - 2, B), X = A + B ).
else fib(N - 1, A), fib(N - 2, B), X = A + B ).
</syntaxhighlight>
</lang>


We've shown the definition of fib/2 again, but the only change here is the memoization pragma (see the reference manual). This is not part of the language specification and different Mercury implementations are allowed to ignore it, however there is only one implementation so in practice memoization is fully supported.
We've shown the definition of fib/2 again, but the only change here is the memoization pragma (see the reference manual). This is not part of the language specification and different Mercury implementations are allowed to ignore it, however there is only one implementation so in practice memoization is fully supported.
Line 6,047: Line 9,211:


=={{header|Metafont}}==
=={{header|Metafont}}==
<lang metafont>vardef fibo(expr n) =
<syntaxhighlight lang="metafont">vardef fibo(expr n) =
if n=0: 0
if n=0: 0
elseif n=1: 1
elseif n=1: 1
Line 6,056: Line 9,220:


for i=0 upto 10: show fibo(i); endfor
for i=0 upto 10: show fibo(i); endfor
end</lang>
end</syntaxhighlight>


=={{header|Microsoft Small Basic}}==
===Iterative===
<lang smallbasic>' Fibonacci sequence - 31/07/2018
n = 139
f1 = 0
f2 = 1
TextWindow.WriteLine("fibo(0)="+f1)
TextWindow.WriteLine("fibo(1)="+f2)
For i = 2 To n
f3 = f1 + f2
TextWindow.WriteLine("fibo("+i+")="+f3)
f1 = f2
f2 = f3
EndFor</lang>
{{out}}
<pre>
fibo(139)=50095301248058391139327916261
</pre>
===Binet's Formula===
<lang smallbasic>' Fibonacci sequence - Binet's Formula - 31/07/2018
n = 69
sq5=Math.SquareRoot(5)
phi1=(1+sq5)/2
phi2=(1-sq5)/2
phi1n=phi1
phi2n=phi2
For i = 2 To n
phi1n=phi1n*phi1
phi2n=phi2n*phi2
TextWindow.Write(Math.Floor((phi1n-phi2n)/sq5)+" ")
EndFor</lang>
{{out}}
<pre>
1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 12586269025 20365011074 32951280099 53316291173 86267571272 139583862445 225851433717 365435296162 591286729879 956722026041 1548008755920 2504730781961 4052739537881 6557470319842 10610209857723 17167680177565 27777890035288 44945570212853 72723460248141 117669030460994
</pre>


=={{header|Mirah}}==
=={{header|min}}==
{{works with|min|0.37.0}}
<lang mirah>def fibonacci(n:int)
<syntaxhighlight lang="min">(
return n if n < 2
(2 <)
fibPrev = 1
(pred (1 0 (over + swap)) dip times pop)
fib = 1
unless
3.upto(Math.abs(n)) do
) ^fib</syntaxhighlight>
oldFib = fib
fib = fib + fibPrev
fibPrev = oldFib
end
fib * (n<0 ? int(Math.pow(n+1, -1)) : 1)
end


=={{header|MiniScript}}==
puts fibonacci 1
An efficient solution (for n >= 0):
puts fibonacci 2
<syntaxhighlight lang="miniscript">fibonacci = function(n)
puts fibonacci 3
if n < 2 then return n
puts fibonacci 4
n1 = 0
puts fibonacci 5
n2 = 1
puts fibonacci 6
for i in range(n-1, 1)
puts fibonacci 7
ans = n1 + n2
</lang>
n1 = n2
n2 = ans
end for
return ans
end function

print fibonacci(6)</syntaxhighlight>

And for comparison, a recursive solution (also for n >= 0):
<syntaxhighlight lang="miniscript">rfib = function(n)
if n < 1 then return 0
if n == 1 then return 1
return rfib(n-1) + rfib(n-2)
end function

print rfib(6)</syntaxhighlight>
=={{header|MiniZinc}}==
<syntaxhighlight lang="minizinc">function var int: fibonacci(int: n) =
let {
array[0..n] of var int: fibonacci;
constraint forall(a in 0..n)(
fibonacci[a] = if (a == 0 \/ a == 1) then
a
else
fibonacci[a-1]+fibonacci[a-2]
endif
)
} in fibonacci[n];
var int: fib = fibonacci(6);
solve satisfy;
output [show(fib),"\n"];</syntaxhighlight>


=={{header|MIPS Assembly}}==
=={{header|MIPS Assembly}}==


This is the iterative approach to the Fibonacci sequence.
This is the iterative approach to the Fibonacci sequence.
<syntaxhighlight lang="mips">
<lang MIPS>
.text
.text
main: li $v0, 5 # read integer from input. The read integer will be stroed in $v0
main: li $v0, 5 # read integer from input. The read integer will be stroed in $v0
Line 6,163: Line 9,319:
li $v0, 10
li $v0, 10
syscall
syscall
</syntaxhighlight>
</lang>

=={{header|Mirah}}==
<syntaxhighlight lang="mirah">def fibonacci(n:int)
return n if n < 2
fibPrev = 1
fib = 1
3.upto(Math.abs(n)) do
oldFib = fib
fib = fib + fibPrev
fibPrev = oldFib
end
fib * (n<0 ? int(Math.pow(n+1, -1)) : 1)
end

puts fibonacci 1
puts fibonacci 2
puts fibonacci 3
puts fibonacci 4
puts fibonacci 5
puts fibonacci 6
puts fibonacci 7
</syntaxhighlight>


=={{header|МК-61/52}}==
=={{header|МК-61/52}}==
<lang>П0 1 lg Вx <-> + L0 03 С/П БП
<syntaxhighlight lang="text">П0 1 lg Вx <-> + L0 03 С/П БП
03</lang>
03</syntaxhighlight>


Instruction: ''n'' В/О С/П, where ''n'' is serial number of the number of Fibonacci sequence; С/П for the following numbers.
Instruction: ''n'' В/О С/П, where ''n'' is serial number of the number of Fibonacci sequence; С/П for the following numbers.
Line 6,173: Line 9,351:
=={{header|ML}}==
=={{header|ML}}==
==={{header|Standard ML}}===
==={{header|Standard ML}}===
====Recursion====
====Tail Recursion====
This version is tail recursive.
This version is tail recursive.
<lang sml>fun fib n =
<syntaxhighlight lang="sml">fun fib n =
let
let
fun fib' (0,a,b) = a
fun fib' (0,a,b) = a
Line 6,181: Line 9,359:
in
in
fib' (n,0,1)
fib' (n,0,1)
end</lang>
end</syntaxhighlight>

====Recursion====
<syntaxhighlight lang="sml">fun fib n = if n < 2 then n else fib (n - 1) + fib (n - 2)</syntaxhighlight>

==={{header|MLite}}===
==={{header|MLite}}===
====Recursion====
====Recursion====
Tail recursive.
Tail recursive.
<lang ocaml>fun fib
<syntaxhighlight lang="ocaml">fun fib
(0, x1, x2) = x2
(0, x1, x2) = x2
| (n, x1, x2) = fib (n-1, x2, x1+x2)
| (n, x1, x2) = fib (n-1, x2, x1+x2)
| n = fib (n, 0, 1)</lang>
| n = fib (n, 0, 1)</syntaxhighlight>


=={{header|ML/I}}==
=={{header|ML/I}}==
<lang ML/I>MCSKIP "WITH" NL
<syntaxhighlight lang="ml/i">MCSKIP "WITH" NL
"" Fibonacci - recursive
"" Fibonacci - recursive
MCSKIP MT,<>
MCSKIP MT,<>
Line 6,205: Line 9,387:
fib(3) is FIB(3)
fib(3) is FIB(3)
fib(4) is FIB(4)
fib(4) is FIB(4)
fib(5) is FIB(5)</lang>
fib(5) is FIB(5)</syntaxhighlight>


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE Fibonacci;
<syntaxhighlight lang="modula2">MODULE Fibonacci;
FROM FormatString IMPORT FormatString;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 6,244: Line 9,426:


ReadChar
ReadChar
END Fibonacci.</lang>
END Fibonacci.</syntaxhighlight>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
===Recursive===
===Recursive===
<lang modula3>PROCEDURE Fib(n: INTEGER): INTEGER =
<syntaxhighlight lang="modula3">PROCEDURE Fib(n: INTEGER): INTEGER =
BEGIN
BEGIN
IF n < 2 THEN
IF n < 2 THEN
Line 6,255: Line 9,437:
RETURN Fib(n-1) + Fib(n-2);
RETURN Fib(n-1) + Fib(n-2);
END;
END;
END Fib;</lang>
END Fib;</syntaxhighlight>


=== Iterative (with negatives) ===
=== Iterative (with negatives) ===


<lang modula3>PROCEDURE IterFib(n: INTEGER): INTEGER =
<syntaxhighlight lang="modula3">PROCEDURE IterFib(n: INTEGER): INTEGER =


VAR
VAR
Line 6,294: Line 9,476:
RETURN curr;
RETURN curr;


END IterFib;</lang>
END IterFib;</syntaxhighlight>


=={{header|Monicelli}}==
=={{header|Monicelli}}==
Recursive version. It includes a main that reads a number N from standard input and prints the Nth Fibonacci number.
Recursive version. It includes a main that reads a number N from standard input and prints the Nth Fibonacci number.
<lang monicelli>
<syntaxhighlight lang="monicelli">
# Main
# Main
Lei ha clacsonato
Lei ha clacsonato
Line 6,311: Line 9,493:
Necchi come se fosse brematurata la supercazzola bonaccia con antani meno 2 o scherziamo? vaffanzum
Necchi come se fosse brematurata la supercazzola bonaccia con antani meno 2 o scherziamo? vaffanzum
unchiamo più duechiamo! e velocità di esecuzione
unchiamo più duechiamo! e velocità di esecuzione
</syntaxhighlight>
</lang>


=={{header|MontiLang}}==
=={{header|MontiLang}}==
Reads number from standard input and prints to that number in the fibonacci sequence
Reads number from standard input and prints to that number in the fibonacci sequence
<lang MontiLang>0 VAR a .
<syntaxhighlight lang="montilang">0 VAR a .
1 VAR b .
1 VAR b .
INPUT TOINT
INPUT TOINT
Line 6,323: Line 9,505:
b VAR a .
b VAR a .
c VAR b .
c VAR b .
ENDFOR</lang>
ENDFOR</syntaxhighlight>

Forth-style solution

<syntaxhighlight lang="montilang">def over
swap dup rot swap
enddef

|Enter a number to obtain Fibonacci sequence: | input nip var count .
0 1
FOR count
over out |, | out . + swap
ENDFOR
. print
input
clear</syntaxhighlight>

Simpler

<syntaxhighlight lang="montilang">|Enter a number to obtain Fibonacci sequence: | input nip 1 - var count .
0 1
FOR count
out |, | out . dup rot +
ENDFOR
print
input /# wait until press ENTER #/
clear /# empties the stack #/</syntaxhighlight>


=={{header|MUMPS}}==
=={{header|MUMPS}}==
===Iterative===
===Iterative===
<lang MUMPS>FIBOITER(N)
<syntaxhighlight lang="mumps">FIBOITER(N)
;Iterative version to get the Nth Fibonacci number
;Iterative version to get the Nth Fibonacci number
;N must be a positive integer
;N must be a positive integer
Line 6,337: Line 9,545:
QUIT:N<2 F(N)
QUIT:N<2 F(N)
FOR I=2:1:N SET F(I)=F(I-1)+F(I-2)
FOR I=2:1:N SET F(I)=F(I-1)+F(I-2)
QUIT F(N)</lang>
QUIT F(N)</syntaxhighlight>


<pre>
<pre>
Line 6,343: Line 9,551:
832040
832040
</pre>
</pre>

=={{header|Nanoquery}}==
===Iterative===
<syntaxhighlight lang="nanoquery">def fibIter(n)
if (n < 2)
return n
end if
$fib = 1
$fibPrev = 1
for num in range(2, n - 1)
fib += fibPrev
fibPrev = fib - fibPrev
end for
return fib
end</syntaxhighlight>


=={{header|Nemerle}}==
=={{header|Nemerle}}==
===Recursive===
===Recursive===
<lang Nemerle>using System;
<syntaxhighlight lang="nemerle">using System;
using System.Console;
using System.Console;


Line 6,363: Line 9,589:
WriteLine("{0}: {1}", n, Fibonacci(n));
WriteLine("{0}: {1}", n, Fibonacci(n));
}
}
}</lang>
}</syntaxhighlight>
===Tail Recursive===
===Tail Recursive===
<lang Nemerle>Fibonacci(x : long, current : long, next : long) : long
<syntaxhighlight lang="nemerle">Fibonacci(x : long, current : long, next : long) : long
{
{
match(x)
match(x)
Line 6,377: Line 9,603:
{
{
Fibonacci(x, 0, 1)
Fibonacci(x, 0, 1)
}</lang>
}</syntaxhighlight>


=={{header|NESL}}==
=={{header|NESL}}==
===Recursive===
===Recursive===
<lang nesl>function fib(n) = if n < 2 then n else fib(n - 2) + fib(n - 1);</lang>
<syntaxhighlight lang="nesl">function fib(n) = if n < 2 then n else fib(n - 2) + fib(n - 1);</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
{{trans|REXX}}
{{trans|REXX}}
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */


options replace format comments java crossref savelog symbols
options replace format comments java crossref savelog symbols
Line 6,422: Line 9,648:
if n > 0 | na // 2 == 1 then return s /*if positive or odd negative... */
if n > 0 | na // 2 == 1 then return s /*if positive or odd negative... */
else return -s /*return a negative Fib number. */
else return -s /*return a negative Fib number. */
</syntaxhighlight>
</lang>


=={{header|NewLISP}}==
=={{header|NewLISP}}==
===Iterative===
===Iterative===
<lang newLISP>(define (fibonacci n)
<syntaxhighlight lang="newlisp">(define (fibonacci n)
(let (L '(0 1))
(let (L '(0 1))
(dotimes (i n)
(dotimes (i n)
(setq L (list (L 1) (apply + L))))
(setq L (list (L 1) (apply + L))))
(L 1)) )
(L 1)) )
</syntaxhighlight>
</lang>


===Recursive===
===Recursive===
<lang newLISP>(define (fibonacci n)
<syntaxhighlight lang="newlisp">(define (fibonacci n)
(if (< n 2) 1
(if (< n 2) 1
(+ (fibonacci (- n 1))
(+ (fibonacci (- n 1))
(fibonacci (- n 2)))))
(fibonacci (- n 2)))))
</syntaxhighlight>
</lang>


===Matrix multiplication===
===Matrix multiplication===
<lang newLISP>(define (fibonacci n)
<syntaxhighlight lang="newlisp">(define (fibonacci n)
(letn (f '((0 1) (1 1)) fib f)
(letn (f '((0 1) (1 1)) fib f)
(dotimes (i n)
(dotimes (i n)
Line 6,447: Line 9,673:
(fib 0 1)) )
(fib 0 1)) )


(print(fibonacci 10)) ;;89</lang>
(print(fibonacci 10)) ;;89</syntaxhighlight>

===With a stack ===
<syntaxhighlight lang="newlisp">
;;; Global variable (bigints); can be isolated in a namespace if need be
(setq stack '(0L 1L))
;
;;; If the stack is too short, complete it; then read from it
;;; Adding at the end of a list is optimized in NewLisp
(define (fib n)
(while (<= (length stack) n)
(push (+ (stack -1) (stack -2)) stack -1))
(stack n))
;
;;; Test (~ 7+ s on my mediocre laptop)
;(println (time (fib 50000)))
;;; or
(println (length (fib 50000)))
;;; outputs 10450 (digits)
</syntaxhighlight>


=={{header|NGS}}==
=={{header|NGS}}==
===Iterative===
===Iterative===
{{trans|Python}}
{{trans|Python}}
<lang NGS>F fib(n:Int) {
<syntaxhighlight lang="ngs">F fib(n:Int) {
n < 2 returns n
n < 2 returns n
local a = 1, b = 1
local a = 1, b = 1
Line 6,462: Line 9,707:
}
}
b
b
}</lang>
}</syntaxhighlight>

=={{header|Nial}}==
===Iterative===
On my machine, about 1.7s for 100,000 iterations, n=92.
Maybe a few percent faster than iterative Python.
Note that n>92 produces overflow; Python keeps going -
single iteration with n=1,000,000 takes it about 15s.

<syntaxhighlight lang="nial">fibi is op n {
if n<2 then
n
else
x1:=0; x2:=1;
for i with tell (n - 1) do
x:=x1+x2;
x1:=x2;
x2:=x;
endfor;
x2
endif};</syntaxhighlight>

Iterative using fold. Slightly faster, <1.6s:

<syntaxhighlight lang="nial">fibf is op n {1 pick ((n- 1) fold [1 pick, +] 0 1)};</syntaxhighlight>

Tacit verion of above. Slightly faster still, <1.4s:

<syntaxhighlight lang="nial">fibf2 is 1 pick fold [1 pick, +] reverse (0 1 hitch) (-1+);</syntaxhighlight>

===Recursive===
Really slow (over 8s for single iteration, n=33).
(Similar to time for recursive python version with n=37.)

<syntaxhighlight lang="nial">fibr is op n {fork [2>, +, + [fibr (-1 +), fibr (-2 +)]] n};</syntaxhighlight>

...or tacit version. More than twice as fast (?) but still slow:

<syntaxhighlight lang="nial">fibr2 is fork [2>, +, + [fibr2 (-1 +), fibr2 (-2 +)]];</syntaxhighlight>

===Matrix===
Matrix inner product (ip).
This appears to be the fastest, about 1.0s for 100,000 iterations, n=92:
Note that n>92 produces negative result.

<syntaxhighlight lang="nial">fibm is op n {floor (0 1 pick (reduce ip (n reshape [2 2 reshape 1 1 1 0])))};</syntaxhighlight>

Could it look a little more like J?
(Maybe 5% slower than above.)

<syntaxhighlight lang="nial">$ is reshape;
~ is tr f op a b {b f a}; % Goes before verb, rather than after like in J;
_ is floor; % Not really J, but J-ish? (Cannot redefine "<.".);

fibm2 is _(0 1 pick reduce ip([2 2$1 1 1 0](~$)));</syntaxhighlight>


Alternate, not involving replicating matrix n times, but maybe 50% slower
than the fastest matrix version above - similar speed to iterative:


<syntaxhighlight lang="nial">fibm3 is op n {a:=2 2$1 1 1 0; _(0 1 pick ((n- 1) fold (a ip) a))};</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
===Analytic===
===Analytic===
<lang nim>proc Fibonacci(n: int): int64 =
<syntaxhighlight lang="nim">proc Fibonacci(n: int): int64 =
var fn = float64(n)
var fn = float64(n)
var p: float64 = (1.0 + sqrt(5.0)) / 2.0
var p: float64 = (1.0 + sqrt(5.0)) / 2.0
var q: float64 = 1.0 / p
var q: float64 = 1.0 / p
return int64((pow(p, fn) + pow(q, fn)) / sqrt(5.0))</lang>
return int64((pow(p, fn) + pow(q, fn)) / sqrt(5.0))</syntaxhighlight>


===Iterative===
===Iterative===
<lang nim>proc Fibonacci(n: int): int =
<syntaxhighlight lang="nim">proc Fibonacci(n: int): int =
var
var
first = 0
first = 0
Line 6,484: Line 9,786:
second += first
second += first


result = first</lang>
result = first</syntaxhighlight>


===Recursive===
===Recursive===
<lang nim>proc Fibonacci(n: int): int64 =
<syntaxhighlight lang="nim">proc Fibonacci(n: int): int64 =
if n <= 2:
if n <= 2:
result = 1
result = 1
else:
else:
result = Fibonacci(n - 1) + Fibonacci(n - 2)</lang>
result = Fibonacci(n - 1) + Fibonacci(n - 2)</syntaxhighlight>


===Tail-recursive===
===Tail-recursive===
<lang nim>proc Fibonacci(n: int, current: int64, next: int64): int64 =
<syntaxhighlight lang="nim">proc Fibonacci(n: int, current: int64, next: int64): int64 =
if n == 0:
if n == 0:
result = current
result = current
Line 6,500: Line 9,802:
result = Fibonacci(n - 1, next, current + next)
result = Fibonacci(n - 1, next, current + next)
proc Fibonacci(n: int): int64 =
proc Fibonacci(n: int): int64 =
result = Fibonacci(n, 0, 1)</lang>
result = Fibonacci(n, 0, 1)</syntaxhighlight>


===Continuations===
===Continuations===
<lang nim>iterator fib: int {.closure.} =
<syntaxhighlight lang="nim">iterator fib: int {.closure.} =
var a = 0
var a = 0
var b = 1
var b = 1
Line 6,513: Line 9,815:
var f = fib
var f = fib
for i in 0.. <10:
for i in 0.. <10:
echo f()</lang>
echo f()</syntaxhighlight>
=={{header|Nix}}==
<syntaxhighlight lang="nix">fibonacci = n:
if n <= 1 then n else (fibonacci (n - 1) + fibonacci (n - 2));</syntaxhighlight>


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
{{Works with|oo2c Version 2}}
{{Works with|oo2c Version 2}}
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE Fibonacci;
MODULE Fibonacci;
IMPORT
IMPORT
Line 6,578: Line 9,883:
GenR(20);
GenR(20);
END Fibonacci.
END Fibonacci.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 6,593: Line 9,898:
=={{header|Objeck}}==
=={{header|Objeck}}==
===Recursive===
===Recursive===
<lang objeck>bundle Default {
<syntaxhighlight lang="objeck">bundle Default {
class Fib {
class Fib {
function : Main(args : String[]), Nil {
function : Main(args : String[]), Nil {
Line 6,609: Line 9,914:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
===Recursive===
===Recursive===
<lang objc>-(long)fibonacci:(int)position
<syntaxhighlight lang="objc">-(long)fibonacci:(int)position
{
{
long result = 0;
long result = 0;
Line 6,622: Line 9,927:
}
}
return result;
return result;
}</lang>
}</syntaxhighlight>
===Iterative===
===Iterative===
<lang objc>+(long)fibonacci:(int)index {
<syntaxhighlight lang="objc">+(long)fibonacci:(int)index {
long beforeLast = 0, last = 1;
long beforeLast = 0, last = 1;
while (index > 0) {
while (index > 0) {
Line 6,632: Line 9,937:
}
}
return last;
return last;
}</lang>
}</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
===Tail-Recursive (fast)===
<syntaxhighlight lang="ocaml">let fib n =
let rec aux i a b =
if i = 0 then a else aux (pred i) b (a + b)
in
aux n 0 1</syntaxhighlight>

===Iterative===
===Iterative===
<lang ocaml>let fib_iter n =
<syntaxhighlight lang="ocaml">let fib_iter n =
if n < 2 then
if n < 2 then
n
n
Line 6,646: Line 9,958:
fib_prev := temp
fib_prev := temp
done;
done;
!fib</lang>
!fib</syntaxhighlight>


===Recursive===
===Recursive===
let rec fib_rec n =
<syntaxhighlight lang="ocaml">let rec fib_rec n =
if n < 2 then
if n < 2 then
n
n
else
else
fib_rec (n - 1) + fib_rec (n - 2)
fib_rec (n - 1) + fib_rec (n - 2)

let rec fib = function
let rec fib = function
0 -> 0
0 -> 0
Line 6,659: Line 9,972:
| n -> if n > 0 then fib (n-1) + fib (n-2)
| n -> if n > 0 then fib (n-1) + fib (n-2)
else fib (n+2) - fib (n+1)
else fib (n+2) - fib (n+1)
</syntaxhighlight>


===Arbitrary Precision===
===Arbitrary Precision===
Using OCaml's [http://caml.inria.fr/pub/docs/manual-ocaml/libref/Num.html Num] module.
Using OCaml's [http://caml.inria.fr/pub/docs/manual-ocaml/libref/Num.html Num] module.


<lang ocaml>open Num
<syntaxhighlight lang="ocaml">open Num


let fib =
let fib =
Line 6,682: Line 9,996:
let n = int_of_string Sys.argv.(1) in
let n = int_of_string Sys.argv.(1) in
print_endline (string_of_num (fib n))
print_endline (string_of_num (fib n))
</syntaxhighlight>
</lang>


compile with:
compile with:
Line 6,700: Line 10,014:
=== O(log(n)) with arbitrary precision ===
=== O(log(n)) with arbitrary precision ===
This performs log2(N) matrix multiplys. Each multiplication is not constant-time but increases sub-linearly, about O(log(N)).
This performs log2(N) matrix multiplys. Each multiplication is not constant-time but increases sub-linearly, about O(log(N)).
<lang ocaml>open Num
<syntaxhighlight lang="ocaml">open Num


let mul (a,b,c) (d,e,f) = let bxe = b*/e in
let mul (a,b,c) (d,e,f) = let bxe = b*/e in
Line 6,715: Line 10,029:
string_of_num y
string_of_num y
;;
;;
Printf.printf "fib %d = %s\n" 300 (fib 300)</lang>
Printf.printf "fib %d = %s\n" 300 (fib 300)</syntaxhighlight>
Output:<pre>fib 300 = 222232244629420445529739893461909967206666939096499764990979600</pre>
Output:<pre>fib 300 = 222232244629420445529739893461909967206666939096499764990979600</pre>

=== Matrix Exponentiation ===
<syntaxhighlight lang="ocaml">
open List
;;
let rec bin n =
if n < 2 then [n mod 2 = 1]
else bin (n/2) @ [n mod 2 = 1]
;;
let cut = function
| [] -> []
| _ :: x -> x
;;
let multiply a b =
let ((p, q), (r, s)) = a in
let ((t, u), (v, w)) = b in
((p*t+q*v, p*u+q*w), (r*t+s*v, r*u+s*w))
;;
let fib n =
let rec f p q r =
if length r = 1 then
if nth r 0 then (multiply p q, q)
else (p, q)
else
let (pp, qq) = f p q (cut r) in
let qqq = multiply qq qq in
if nth r 0 then (multiply pp qqq, qqq)
else (pp, qqq) in
f ((1L, 0L), (0L, 1L)) ((1L, 1L), (1L, 0L)) (bin n) |> fst |> fst |> snd
;;
</syntaxhighlight>


=={{header|Octave}}==
=={{header|Octave}}==
'''Recursive'''
===Recursive===
<lang octave>% recursive
<syntaxhighlight lang="octave">% recursive
function fibo = recfibo(n)
function fibo = recfibo(n)
if ( n < 2 )
if ( n < 2 )
Line 6,727: Line 10,072:
fibo = recfibo(n-1) + recfibo(n-2);
fibo = recfibo(n-1) + recfibo(n-2);
endif
endif
endfunction</lang>
endfunction</syntaxhighlight>


'''Iterative'''
'''Testing'''
<lang octave>% iterative
<syntaxhighlight lang="octave">% testing
for i = 0 : 20
printf("%d %d\n", i, recfibo(i));
endfor</syntaxhighlight>

===Iterative===
<syntaxhighlight lang="octave">% iterative
function fibo = iterfibo(n)
function fibo = iterfibo(n)
if ( n < 2 )
if ( n < 2 )
Line 6,745: Line 10,096:
fibo = f(2);
fibo = f(2);
endif
endif
endfunction</lang>
endfunction</syntaxhighlight>


'''Testing'''
'''Testing'''
<lang octave>% testing
<syntaxhighlight lang="octave">% testing
for i = 0 : 20
for i = 0 : 20
printf("%d %d\n", iterfibo(i), recfibo(i));
printf("%d %d\n", i, iterfibo(i));
endfor</lang>
endfor</syntaxhighlight>

===Analytic===
<syntaxhighlight lang="octave">function retval = fibanalytic(n)
retval = round(((5 .^ 0.5 + 1) / 2) .^ n / 5 .^ 0.5);
endfunction</syntaxhighlight>

===Tail Recursive===
<syntaxhighlight lang="octave">function retval = fibtailrecursive(n, prevfib = 0, fib = 1)
if (n == 0)
retval = prevfib;
else
retval = fibtailrecursive(n - 1, fib, prevfib + fib);
endif
endfunction</syntaxhighlight>

=={{header|Odin}}==
Fibinacci Sequence - Iterative Solution<br>
Odin Build: dev-2023-07-nightly:3072479c
<syntaxhighlight lang="odin">
package fib
import "core:fmt"

main :: proc() {
fmt.println("\nFibonacci Seq - starting n and n+1 from 0 and 1:")
fmt.println("------------------------------------------------")
for j: u128 = 0; j <= 20; j += 1 {
fmt.println("n:", j, "\tFib:", fibi(j))
}
}

fibi :: proc(n: u128) -> u128 {
if n < 2 {
return n
}
a, b: u128 = 0, 1
for _ in 2..=n {
a += b
a, b = b, a
}
return b
}
</syntaxhighlight>
{{out}}
<pre>
First 20 Fibonacci Numbers
Starting n and n+1 from 0 and 1
-------------------------------
n: 0 Fib: 0
n: 1 Fib: 1
n: 2 Fib: 1
n: 3 Fib: 2
n: 4 Fib: 3
n: 5 Fib: 5
n: 6 Fib: 8
n: 7 Fib: 13
n: 8 Fib: 21
n: 9 Fib: 34
n: 10 Fib: 55
n: 11 Fib: 89
n: 12 Fib: 144
n: 13 Fib: 233
n: 14 Fib: 377
n: 15 Fib: 610
n: 16 Fib: 987
n: 17 Fib: 1597
n: 18 Fib: 2584
n: 19 Fib: 4181
n: 20 Fib: 6765
-------------------------------
</pre>


=={{header|Oforth}}==
=={{header|Oforth}}==
<lang Oforth>: fib 0 1 rot #[ tuck + ] times drop ;</lang>
<syntaxhighlight lang="oforth">: fib 0 1 rot #[ tuck + ] times drop ;</syntaxhighlight>

=={{header|Ol}}==
Same as [https://rosettacode.org/wiki/Fibonacci_sequence#Scheme Scheme] example(s).

=={{header|Onyx (wasm)}}==
<syntaxhighlight lang="C">
use core.iter
use core { printf }

// Procedural Simple For-Loop Style
fib_for_loop :: (n: i32) -> i32 {
a: i32 = 0;
b: i32 = 1;
for 0 .. n {
tmp := a;
a = b;
b = tmp + b;
}
return a;
}

FibState :: struct { a, b: u64 }

// Functional Folding Style
fib_by_fold :: (n: i32) => {
end_state :=
iter.counter()
|> iter.take(n)
|> iter.fold(
FibState.{ a = 0, b = 1 },
(_, state) => FibState.{
a = state.b,
b = state.a + state.b
}
);
return end_state.a;
}

// Custom Iterator Style
fib_iterator :: (n: i32) =>
iter.generator(
&.{ a = cast(u64) 0, b = cast(u64) 1, counter = n },
(state: & $Ctx) -> (u64, bool) {
if state.counter <= 0 {
return 0, false;
}
tmp := state.a;
state.a = state.b;
state.b = state.b + tmp;
state.counter -= 1;
return tmp, true;
}
);

main :: () {
printf("\nBy For Loop:\n");
for i in 0 .. 21 {
printf("{} ", fib_for_loop(i));
}

printf("\n\nBy Iterator:\n");
for i in 0 .. 21 {
printf("{} ", fib_by_fold(i));
}

printf("\n\nBy Fold:\n");
for value, index in fib_iterator(21) {
printf("{} ", value);
}
}
</syntaxhighlight>
{{out}}
<pre>
For-Loop:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765

Functional Fold:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765

Custom Iterator:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
</pre>


=={{header|OPL}}==
=={{header|OPL}}==
<lang opl>FIBON:
<syntaxhighlight lang="opl">FIBON:
REM Fibonacci sequence is generated to the Organiser II floating point variable limit.
REM Fibonacci sequence is generated to the Organiser II floating point variable limit.
REM CLEAR/ON key quits.
REM CLEAR/ON key quits.
Line 6,769: Line 10,272:
B=C
B=C
PRINT A,
PRINT A,
UNTIL GET=1</lang>
UNTIL GET=1</syntaxhighlight>


=={{header|Order}}==
=={{header|Order}}==
===Recursive===
===Recursive===
<lang c>#include <order/interpreter.h>
<syntaxhighlight lang="c">#include <order/interpreter.h>


#define ORDER_PP_DEF_8fib_rec \
#define ORDER_PP_DEF_8fib_rec \
Line 6,782: Line 10,285:
8fib_rec(8sub(8N, 2))))))
8fib_rec(8sub(8N, 2))))))


ORDER_PP(8fib_rec(10))</lang>
ORDER_PP(8fib_rec(10))</syntaxhighlight>


Tail recursive version (example supplied with language):
Tail recursive version (example supplied with language):
<lang c>#include <order/interpreter.h>
<syntaxhighlight lang="c">#include <order/interpreter.h>
#define ORDER_PP_DEF_8fib \
#define ORDER_PP_DEF_8fib \
Line 6,797: Line 10,300:
8fib_iter(8dec(8N), 8J, 8add(8I, 8J)))))
8fib_iter(8dec(8N), 8J, 8add(8I, 8J)))))
ORDER_PP(8to_lit(8fib(8nat(5,0,0))))</lang>
ORDER_PP(8to_lit(8fib(8nat(5,0,0))))</syntaxhighlight>


===Memoization===
===Memoization===
<lang c>#include <order/interpreter.h>
<syntaxhighlight lang="c">#include <order/interpreter.h>


#define ORDER_PP_DEF_8fib_memo \
#define ORDER_PP_DEF_8fib_memo \
Line 6,824: Line 10,327:
8print(8to_lit(8fib_memo(8N)) (,) 8space)),
8print(8to_lit(8fib_memo(8N)) (,) 8space)),
1, 21)
1, 21)
)</lang>
)</syntaxhighlight>


=={{header|Oz}}==
=={{header|Oz}}==
Line 6,830: Line 10,333:
===Iterative===
===Iterative===
Using mutable references (cells).
Using mutable references (cells).
<lang oz>fun{FibI N}
<syntaxhighlight lang="oz">fun{FibI N}
Temp = {NewCell 0}
Temp = {NewCell 0}
A = {NewCell 0}
A = {NewCell 0}
Line 6,841: Line 10,344:
end
end
@A
@A
end</lang>
end</syntaxhighlight>


===Recursive===
===Recursive===
Inefficient (blows up the stack).
Inefficient (blows up the stack).
<lang oz>fun{FibR N}
<syntaxhighlight lang="oz">fun{FibR N}
if N < 2 then N
if N < 2 then N
else {FibR N-1} + {FibR N-2}
else {FibR N-1} + {FibR N-2}
end
end
end</lang>
end</syntaxhighlight>


===Tail-recursive===
===Tail-recursive===
Using accumulators.
Using accumulators.
<lang oz>fun{Fib N}
<syntaxhighlight lang="oz">fun{Fib N}
fun{Loop N A B}
fun{Loop N A B}
if N == 0 then
if N == 0 then
Line 6,863: Line 10,366:
in
in
{Loop N 1 0}
{Loop N 1 0}
end</lang>
end</syntaxhighlight>


===Lazy-recursive===
===Lazy-recursive===
<lang oz>declare
<syntaxhighlight lang="oz">declare
fun lazy {FiboSeq}
fun lazy {FiboSeq}
{LazyMap
{LazyMap
Line 6,885: Line 10,388:
end
end
in
in
{Show {List.take {FiboSeq} 8}}</lang>
{Show {List.take {FiboSeq} 8}}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
===Built-in===
===Built-in===
<lang parigp>fibonocci(n)</lang>
<syntaxhighlight lang="parigp">fibonacci(n)</syntaxhighlight>


===Matrix===
===Matrix===
<lang parigp>fib(n)=([1,1;1,0]^n)[1,2]</lang>
<syntaxhighlight lang="parigp">fib(n)=([1,1;1,0]^n)[1,2]</syntaxhighlight>


===Analytic===
===Analytic===
This uses the Binet form.
This uses the Binet form.
<lang parigp>fib(n)=my(phi=(1+sqrt(5))/2);round((phi^n-phi^-n)/sqrt(5))</lang>
<syntaxhighlight lang="parigp">fib(n)=my(phi=(1+sqrt(5))/2);round((phi^n-phi^-n)/sqrt(5))</syntaxhighlight>
The second term can be dropped since the error is always small enough to be subsumed by the rounding.
The second term can be dropped since the error is always small enough to be subsumed by the rounding.
<lang parigp>fib(n)=round(((1+sqrt(5))/2)^n/sqrt(5))</lang>
<syntaxhighlight lang="parigp">fib(n)=round(((1+sqrt(5))/2)^n/sqrt(5))</syntaxhighlight>


===Algebraic===
===Algebraic===
Line 6,905: Line 10,408:
and hence <code>real(quadgen(5)^n)</code> would give the (n-1)-th Fibonacci number.
and hence <code>real(quadgen(5)^n)</code> would give the (n-1)-th Fibonacci number.


<lang parigp>fib(n)=imag(quadgen(5)^n)</lang>
<syntaxhighlight lang="parigp">fib(n)=imag(quadgen(5)^n)</syntaxhighlight>


A more direct translation (note that <math>\sqrt5=2\phi-1</math>) would be
A more direct translation (note that <math>\sqrt5=2\phi-1</math>) would be
<lang parigp>fib(n)=my(phi=quadgen(5));(phi^n-(-1/phi)^n)/(2*phi-1)</lang>
<syntaxhighlight lang="parigp">fib(n)=my(phi=quadgen(5));(phi^n-(-1/phi)^n)/(2*phi-1)</syntaxhighlight>


===Combinatorial===
===Combinatorial===
This uses the generating function. It can be trivially adapted to give the first n Fibonacci numbers.
This uses the generating function. It can be trivially adapted to give the first n Fibonacci numbers.
<lang parigp>fib(n)=polcoeff(x/(1-x-x^2)+O(x^(n+1)),n)</lang>
<syntaxhighlight lang="parigp">fib(n)=polcoeff(x/(1-x-x^2)+O(x^(n+1)),n)</syntaxhighlight>


===Binary powering===
===Binary powering===
<lang parigp>fib(n)={
<syntaxhighlight lang="parigp">fib(n)={
if(n<=0,
if(n<=0,
if(n,(-1)^(n+1)*fib(n),0)
if(n,(-1)^(n+1)*fib(n),0)
Line 6,932: Line 10,435:
if(n,[v[1]^2+2,v[1]*v[2]+1],[v[1]^2-2,v[1]*v[2]-1])
if(n,[v[1]^2+2,v[1]*v[2]+1],[v[1]^2-2,v[1]*v[2]-1])
)
)
};</lang>
};</syntaxhighlight>


===Recursive===
===Recursive===
<lang parigp>fib(n)={
<syntaxhighlight lang="parigp">fib(n)={
if(n<2,
if(n<2,
n
n
Line 6,941: Line 10,444:
fib(n-1)+fib(n)
fib(n-1)+fib(n)
)
)
};</lang>
};</syntaxhighlight>


===Anonymous recursion===
===Anonymous recursion===
{{works with|PARI/GP|2.8.0+}}
{{works with|PARI/GP|2.8.0+}}
This uses <code>self()</code> which gives a self-reference.
This uses <code>self()</code> which gives a self-reference.
<lang parigp>fib(n)={
<syntaxhighlight lang="parigp">fib(n)={
if(n<2,
if(n<2,
n
n
Line 6,953: Line 10,456:
s(n-2)+s(n-1)
s(n-2)+s(n-1)
)
)
};</lang>
};</syntaxhighlight>


It can be used without being named:
It can be used without being named:
<lang parigp>apply(n->if(n<2,n,my(s=self());s(n-2)+s(n-1)), [1..10])</lang>
<syntaxhighlight lang="parigp">apply(n->if(n<2,n,my(s=self());s(n-2)+s(n-1)), [1..10])</syntaxhighlight>
gives
gives
{{out}}
{{out}}
Line 6,962: Line 10,465:


===Memoization===
===Memoization===
<lang parigp>F=[];
<syntaxhighlight lang="parigp">F=[];
fib(n)={
fib(n)={
if(n>#F,
if(n>#F,
Line 6,974: Line 10,477:
)
)
);
);
}</lang>
}</syntaxhighlight>


===Iterative===
===Iterative===
<lang parigp>fib(n)={
<syntaxhighlight lang="parigp">fib(n)={
if(n<0,return((-1)^(n+1)*fib(n)));
if(n<0,return((-1)^(n+1)*fib(n)));
my(a=0,b=1,t);
my(a=0,b=1,t);
Line 6,987: Line 10,490:
);
);
a
a
};</lang>
};</syntaxhighlight>


===Chebyshev===
===Chebyshev===
This solution uses Chebyshev polynomials of the second kind (Chyebyshev U-polynomials).
This solution uses Chebyshev polynomials of the second kind (Chyebyshev U-polynomials).
<lang parigp>fib(n)=n--;polchebyshev(n,2,I/2)*I^n;</lang>
<syntaxhighlight lang="parigp">fib(n)=n--;polchebyshev(n,2,I/2)*I^n;</syntaxhighlight>
or
or
<lang parigp>fib(n)=abs(polchebyshev(n-1,2,I/2));</lang>
<syntaxhighlight lang="parigp">fib(n)=abs(polchebyshev(n-1,2,I/2));</syntaxhighlight>


===Anti-Hadamard matrix===
===Anti-Hadamard matrix===
Line 6,999: Line 10,502:
R. L. Graham and N. J. A. Sloane, [http://www.math.ucsd.edu/~ronspubs/84_03_anti_hadamard.pdf Anti-Hadamard matrices], Linear Algebra Appl. 62 (1984), 113–137.</ref> matches this upper bound, and hence can be used as an inefficient method for computing Fibonacci numbers of positive index. These matrices are the same as Matlab's type-3 "Dramadah" matrices, following a naming suggestion of C. L. Mallows according to Graham & Sloane.
R. L. Graham and N. J. A. Sloane, [http://www.math.ucsd.edu/~ronspubs/84_03_anti_hadamard.pdf Anti-Hadamard matrices], Linear Algebra Appl. 62 (1984), 113–137.</ref> matches this upper bound, and hence can be used as an inefficient method for computing Fibonacci numbers of positive index. These matrices are the same as Matlab's type-3 "Dramadah" matrices, following a naming suggestion of C. L. Mallows according to Graham & Sloane.


<lang parigp>matantihadamard(n)={
<syntaxhighlight lang="parigp">matantihadamard(n)={
matrix(n,n,i,j,
matrix(n,n,i,j,
my(t=j-i+1);
my(t=j-i+1);
Line 7,005: Line 10,508:
);
);
}
}
fib(n)=matdet(matantihadamard(n))</lang>
fib(n)=matdet(matantihadamard(n))</syntaxhighlight>




===Testing adjacent bits===
===Testing adjacent bits===
The Fibonacci numbers can be characterized (for n > 0) as the number of n-bit strings starting and ending with 1 without adjacent 0s. This inefficient, exponential-time algorithm demonstrates:
The Fibonacci numbers can be characterized (for n > 0) as the number of n-bit strings starting and ending with 1 without adjacent 0s. This inefficient, exponential-time algorithm demonstrates:
<lang parigp>fib(n)=
<syntaxhighlight lang="parigp">fib(n)=
{
{
my(g=2^(n+1)-1);
my(g=2^(n+1)-1);
Line 7,016: Line 10,519:
bitor(i,i<<1)==g
bitor(i,i<<1)==g
);
);
}</lang>
}</syntaxhighlight>


===One-by-one===
===One-by-one===
This code is purely for amusement and requires n > 1. It tests numbers in order to see if they are Fibonacci numbers, and waits until it has seen ''n'' of them.
This code is purely for amusement and requires n > 1. It tests numbers in order to see if they are Fibonacci numbers, and waits until it has seen ''n'' of them.
<lang parigp>fib(n)=my(k=0);while(n--,k++;while(!issquare(5*k^2+4)&&!issquare(5*k^2-4),k++));k</lang>
<syntaxhighlight lang="parigp">fib(n)=my(k=0);while(n--,k++;while(!issquare(5*k^2+4)&&!issquare(5*k^2-4),k++));k</syntaxhighlight>

=={{header|ParaCL}}==
<syntaxhighlight lang="parasl">
fibbonachi = func(x) : fibb
{
res = 1;
if (x > 1)
res = fibb(x - 1) + fibb(x - 2);
res;
}
</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
===Analytic===
===Analytic===
<lang pascal>function fib(n: integer):longInt;
<syntaxhighlight lang="pascal">function fib(n: integer):longInt;
const
const
Sqrt5 = sqrt(5.0);
Sqrt5 = sqrt(5.0);
Line 7,040: Line 10,554:
else
else
Fibdirekt := 0
Fibdirekt := 0
end;</lang>
end;</syntaxhighlight>


===Recursive===
===Recursive===
<lang pascal>function fib(n: integer): integer;
<syntaxhighlight lang="pascal">function fib(n: integer): integer;
begin
begin
if (n = 0) or (n = 1)
if (n = 0) or (n = 1)
Line 7,050: Line 10,564:
else
else
fib := fib(n-1) + fib(n-2)
fib := fib(n-1) + fib(n-2)
end;</lang>
end;</syntaxhighlight>


===Iterative===
===Iterative===
<lang pascal>function fib(n: integer): integer;
<syntaxhighlight lang="pascal">function fib(n: integer): integer;
var
var
f0, f1, tmpf0, k: integer;
f0, f1, tmpf0, k: integer;
Line 7,074: Line 10,588:
f1 := 0;
f1 := 0;
fib := f1;
fib := f1;
end;</lang>
end;</syntaxhighlight>


===Analytic2===
===Analytic2===
<lang pascal>function FiboMax(n: integer):Extended; //maXbox
<syntaxhighlight lang="pascal">function FiboMax(n: integer):Extended; //maXbox
begin
begin
result:= (pow((1+SQRT5)/2,n)-pow((1-SQRT5)/2,n))/SQRT5
result:= (pow((1+SQRT5)/2,n)-pow((1-SQRT5)/2,n))/SQRT5
end;</lang>
end;</syntaxhighlight>




<lang pascal>function Fibo_BigInt(n: integer): string; //maXbox
<syntaxhighlight lang="pascal">function Fibo_BigInt(n: integer): string; //maXbox
var tbig1, tbig2, tbig3: TInteger;
var tbig1, tbig2, tbig3: TInteger;
begin
begin
Line 7,100: Line 10,614:
tbig2.free;
tbig2.free;
tbig1.free;
tbig1.free;
end;</lang>
end;</syntaxhighlight>


writeln(floattoStr(FiboMax(555)))
writeln(floattoStr(FiboMax(555)))
Line 7,108: Line 10,622:
>>>43516638122555047989641805373140394725407202037260729735885664398655775748034950972577909265605502785297675867877570
>>>43516638122555047989641805373140394725407202037260729735885664398655775748034950972577909265605502785297675867877570


===Doubling (iterative)===
The Clojure solution gives a recursive version of the Fibonacci doubling algorithm. The code below is an iterative version, written in Free Pascal. The unsigned 64-bit integer type can hold Fibonacci numbers up to F[93].
<syntaxhighlight lang="pascal">
program Fibonacci_console;

{$mode objfpc}{$H+}

uses SysUtils;

function Fibonacci( n : word) : uint64;
{
Starts with the pair F[0],F[1]. At each iteration, uses the doubling formulae
to pass from F[k],F[k+1] to F[2k],F[2k+1]. If the current bit of n (starting
from the high end) is 1, there is a further step to F[2k+1],F[2k+2].
}
var
marker, half_n : word;
f, g : uint64; // pair of consecutive Fibonacci numbers
t, u : uint64; // -----"-----
begin
// The values of F[0], F[1], F[2] are assumed to be known
case n of
0 : result := 0;
1, 2 : result := 1;
else begin
half_n := n shr 1;
marker := 1;
while marker <= half_n do marker := marker shl 1;

// First time: current bit is 1 by construction,
// so go straight from F[0],F[1] to F[1],F[2].
f := 1; // = F[1]
g := 1; // = F[2]
marker := marker shr 1;

while marker > 1 do begin
t := f*(2*g - f);
u := f*f + g*g;
if (n and marker = 0) then begin
f := t;
g := u;
end
else begin
f := u;
g := t + u;
end;
marker := marker shr 1;
end;

// Last time: we need only one of the pair.
if (n and marker = 0) then
result := f*(2*g - f)
else
result := f*f + g*g;
end; // end else (i.e. n > 2)
end; // end case
end;

// Main program
var
n : word;
begin
for n := 0 to 93 do
WriteLn( SysUtils.Format( 'F[%2u] = %20u', [n, Fibonacci(n)]));
end.
</syntaxhighlight>
{{out}}
<pre>
F[ 0] = 0
F[ 1] = 1
F[ 2] = 1
F[ 3] = 2
F[ 4] = 3
F[ 5] = 5
F[ 6] = 8
F[ 7] = 13
[...]
F[90] = 2880067194370816120
F[91] = 4660046610375530309
F[92] = 7540113804746346429
F[93] = 12200160415121876738
</pre>

=={{header|PascalABC.NET}}==
Uses functionality from [[Fibonacci n-step number sequences#PascalABC.NET]]
<syntaxhighlight lang="pascal">
// Fibonacci sequence. Nigel Galloway: August 30th., 2022
begin
unfold(nFib,0bi,1bi).ElementAt(1000).Println;
end.
</syntaxhighlight>
<pre>
43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875
</pre>
=={{header|Perl}}==
=={{header|Perl}}==
===Iterative===
===Iterative===
<lang perl>sub fib_iter {
<syntaxhighlight lang="perl">sub fib_iter {
my $n = shift;
my $n = shift;
use bigint try => "GMP,Pari";
use bigint try => "GMP,Pari";
Line 7,116: Line 10,724:
($v2,$v1) = ($v1,$v2+$v1) for 0..$n;
($v2,$v1) = ($v1,$v2+$v1) for 0..$n;
$v1;
$v1;
}</lang>
}</syntaxhighlight>


===Recursive===
===Recursive===
<lang perl>sub fibRec {
<syntaxhighlight lang="perl">sub fibRec {
my $n = shift;
my $n = shift;
$n < 2 ? $n : fibRec($n - 1) + fibRec($n - 2);
$n < 2 ? $n : fibRec($n - 1) + fibRec($n - 2);
}</lang>
}</syntaxhighlight>


===Modules===
===Modules===
Quite a few modules have ways to do this. Performance is not typically an issue with any of these until 100k or so. With GMP available, the first three are ''much'' faster at large values.
Quite a few modules have ways to do this. Performance is not typically an issue with any of these until 100k or so. With GMP available, the first three are ''much'' faster at large values.
<lang perl># Uses GMP method so very fast
<syntaxhighlight lang="perl"># Uses GMP method so very fast
use Math::AnyNum qw/fibonacci/;
use Math::AnyNum qw/fibonacci/;
say fibonacci(10000);
say fibonacci(10000);
Line 7,149: Line 10,757:
# Perl, gives floating point *approximation*
# Perl, gives floating point *approximation*
use Math::Fibonacci qw/term/;
use Math::Fibonacci qw/term/;
say term(10000);</lang>
say term(10000);</syntaxhighlight>


===Array accumulation===
=={{header|Perl 6}}==
<p>This solution accumulates all Fibonacci numbers up to <i>n</i> into an array of <i>n</i>+1 elements (to account for the zeroth Fibonacci number). When the loop reaches <i>n</i>, the function returns the last element of the array, i.e. the <i>n</i>-th Fibonacci number. This function only works for positive integers, but it can be easily extended into negatives.</p>
<p>Note that, without the use of big integer libraries, pure Perl switches to floats in scientific notation above <i>n</i>=93 and treats any number as infinite above <i>n</i>=1476 (see output). This behaviour could vary across Perl implementations.</p>
<syntaxhighlight lang = "Perl>
sub fibonacci {
my $n = shift;
return 0 if $n < 1;
return 1 if $n == 1;
my @numbers = (0, 1);


push @numbers, $numbers[-1] + $numbers[-2] foreach 2 .. $n;
===List Generator===
return $numbers[-1];
}


print "Fibonacci($_) -> ", (fibonacci $_), "\n"
This constructs the fibonacci sequence as a lazy infinite list.
foreach (0 .. 20, 50, 93, 94, 100, 200, 1000, 1476, 1477);
<lang perl6>constant @fib = 0, 1, *+* ... *;</lang>
</syntaxhighlight>


{{out}}
If you really need a function for it:
<pre>
<lang perl6>sub fib ($n) { @fib[$n] }</lang>
Fibonacci(0) -> 0

Fibonacci(1) -> 1
To support negative indices:
Fibonacci(2) -> 1
<lang perl6>constant @neg-fib = 0, 1, *-* ... *;
Fibonacci(3) -> 2
sub fib ($n) { $n >= 0 ?? @fib[$n] !! @neg-fib[-$n] }</lang>
Fibonacci(4) -> 3

Fibonacci(5) -> 5
===Iterative===
Fibonacci(6) -> 8
<lang perl6>sub fib (Int $n --> Int) {
Fibonacci(7) -> 13
$n > 1 or return $n;
Fibonacci(8) -> 21
my ($prev, $this) = 0, 1;
Fibonacci(9) -> 34
($prev, $this) = $this, $this + $prev for 1 ..^ $n;
Fibonacci(10) -> 55
return $this;
Fibonacci(11) -> 89
}</lang>
Fibonacci(12) -> 144

Fibonacci(13) -> 233
===Recursive===
Fibonacci(14) -> 377
<lang perl6>proto fib (Int $n --> Int) {*}
Fibonacci(15) -> 610
multi fib (0) { 0 }
Fibonacci(16) -> 987
multi fib (1) { 1 }
Fibonacci(17) -> 1597
multi fib ($n) { fib($n - 1) + fib($n - 2) }</lang>
Fibonacci(18) -> 2584

Fibonacci(19) -> 4181
===Analytic===
Fibonacci(20) -> 6765
<lang perl6>sub fib (Int $n --> Int) {
Fibonacci(50) -> 12586269025
constant φ1 = 1 / constant φ = (1 + sqrt 5)/2;
Fibonacci(93) -> 12200160415121876738
constant invsqrt5 = 1 / sqrt 5;
Fibonacci(94) -> 1.97402742198682e+19

Fibonacci(100) -> 3.54224848179262e+20
floor invsqrt5 * (φ**$n + φ1**$n);
Fibonacci(200) -> 2.8057117299251e+41
}</lang>
Fibonacci(1000) -> 4.34665576869374e+208
Fibonacci(1476) -> 1.3069892237634e+308
Fibonacci(1477) -> Inf
</pre>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
{{libheader|bigatom}}
<lang Phix>function fibonacci(integer n) -- iterative, works for -ve numbers
<span style="color: #008080;">function</span> <span style="color: #000000;">fibonacci</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: #000080;font-style:italic;">-- iterative, works for -ve numbers</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span>
atom a=0, b=1
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if n=0 then return 0 end if
<span style="color: #008080;">if</span> <span style="color: #7060A8;">abs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)>=</span><span style="color: #000000;">79</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #000080;font-style:italic;">-- inaccuracies creep in above 78</span>
if abs(n)>=79 then ?9/0 end if -- inaccuracies creep in above 78
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">abs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
for i=1 to abs(n)-1 do
<span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">+</span><span style="color: #000000;">b</span><span style="color: #0000FF;">}</span>
{a,b} = {b,a+b}
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end for
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">b</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if n<0 and remainder(n,2)=0 then return -fcache[absn] end if
<span style="color: #008080;">return</span> <span style="color: #000000;">b</span>
return fcache[absn]
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
end function

<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">28</span> <span style="color: #008080;">do</span>
for i=0 to 28 do
<span style="color: #008080;">if</span> <span style="color: #000000;">i</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">", "</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if i then puts(1,", ") end if
<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;">"%d"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fibonacci</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">))</span>
printf(1,"%d", fibonacci(i))
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end for
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
puts(1,"\n")</lang>
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811
</pre>
</pre>
Using native integers/atoms, errors creep in above 78, so the same program converted to use bigatoms, and memoized:
Using native integers/atoms, errors creep in above 78, so the same program converted to use mpfr:
{{libheader|Phix/mpfr}}
<lang Phix>include builtins\bigatom.e
<!--<syntaxhighlight lang="phix">(phixonline)-->

<span style="color: #000080;font-style:italic;">-- demo\rosetta\fibonacci.exw</span>
sequence fcacheba = {BA_ONE,BA_ONE}
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>

<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
function fibonamemba(integer n) -- memoized, works for -ve numbers, yields bigatom
integer absn = abs(n)
<span style="color: #004080;">mpz</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">NULL</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">prev</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">next</span>
if n=0 then return BA_ZERO end if
<span style="color: #004080;">integer</span> <span style="color: #000000;">lastn</span>
while length(fcacheba)<absn do
<span style="color: #004080;">atom</span> <span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()</span>
fcacheba = append(fcacheba,ba_add(fcacheba[$],fcacheba[$-1]))
<span style="color: #008080;">function</span> <span style="color: #000000;">fibonampz</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: #000080;font-style:italic;">-- resumable, works for -ve numbers, yields mpz</span>
end while
<span style="color: #004080;">integer</span> <span style="color: #000000;">absn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">abs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
if n<0 and remainder(n,2)=0 then return ba_sub(0,fcacheba[absn]) end if
<span style="color: #008080;">if</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">=</span><span style="color: #004600;">NULL</span> <span style="color: #008080;">or</span> <span style="color: #000000;">absn</span><span style="color: #0000FF;">!=</span><span style="color: #7060A8;">abs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lastn</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
return fcacheba[absn]
<span style="color: #008080;">if</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">=</span><span style="color: #004600;">NULL</span> <span style="color: #008080;">then</span>
end function
<span style="color: #000000;">prev</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>

<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
for i=0 to 28 do
<span style="color: #000000;">next</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">()</span>
if i then puts(1,", ") end if
<span style="color: #008080;">else</span>
ba_printf(1,"%B", fibonamemba(i))
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">==</span><span style="color: #000000;">lastn</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #000000;">res</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
puts(1,"\n")
<span style="color: #7060A8;">mpz_fib2_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">prev</span><span style="color: #0000FF;">,</span><span style="color: #000000;">absn</span><span style="color: #0000FF;">)</span>
ba_printf(1,"%B", fibonamemba(705))
<span style="color: #008080;">else</span>
puts(1,"\n")</lang>
<span style="color: #008080;">if</span> <span style="color: #000000;">lastn</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lastn</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">mpz_mul_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</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;">if</span>
<span style="color: #7060A8;">mpz_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">next</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">prev</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">prev</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">next</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">next</span><span style="color: #0000FF;">,</span><span style="color: #000000;">prev</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">mpz_mul_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</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;">if</span>
<span style="color: #000000;">lastn</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">28</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">i</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">", "</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</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;">"%s"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fibonampz</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">))})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</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;">"%s\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fibonampz</span><span style="color: #0000FF;">(</span><span style="color: #000000;">705</span><span style="color: #0000FF;">))})</span>
<span style="color: #000080;font-style:italic;">-- not surprisingly JavaScript BigInt takes a bit
-- longer for 0.1M digits that gmp does for 1.0M:</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">big</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()==</span><span style="color: #004600;">JS</span><span style="color: #0000FF;">?</span><span style="color: #000000;">478495</span><span style="color: #0000FF;">:</span><span style="color: #000000;">4784969</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fibonampz</span><span style="color: #0000FF;">(</span><span style="color: #000000;">big</span><span style="color: #0000FF;">))</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811
970066202977562212558683426760773016559904631977220423547980211057068777324159443678590358026859129109599109446646966713225742014317926940054191330
970066202977562212558683426760773016559904631977220423547980211057068777324159443678590358026859129109599109446646966713225742014317926940054191330
{1000000,"107273956418004772293648135962250043219...407167474856539211500699706378405156269"}
"2.1s"
</pre>
</pre>

=={{header|Phixmonti}}==
<syntaxhighlight lang="phixmonti">def Fibonacci
dup 0 < if
"Invalid argument: " print
else
1 1 rot 2 -
for
drop
over over +
endfor
endif
enddef

10 Fibonacci pstack print nl
-10 Fibonacci print</syntaxhighlight>


=={{header|PHP}}==
=={{header|PHP}}==
===Iterative===
===Iterative===
<lang php>function fibIter($n) {
<syntaxhighlight lang="php">function fibIter($n) {
if ($n < 2) {
if ($n < 2) {
return $n;
return $n;
Line 7,249: Line 10,921:
}
}
return $fib;
return $fib;
}</lang>
}</syntaxhighlight>
===Recursive===
===Recursive===
<lang php>function fibRec($n) {
<syntaxhighlight lang="php">function fibRec($n) {
return $n < 2 ? $n : fibRec($n-1) + fibRec($n-2);
return $n < 2 ? $n : fibRec($n-1) + fibRec($n-2);
}</lang>
}</syntaxhighlight>

=={{header|Picat}}==
===Function===
tabling for speed.
<syntaxhighlight lang="picat">go =>
println([fib_fun(I) : I in 1..10]),
F1=fib_fun(2**10),
println(f1=F1),
nl.

table
fib_fun(0) = 0.
fib_fun(1) = 1.
fib_fun(N) = fib_fun(N-1) + fib_fun(N-2).</syntaxhighlight>

{{out}}
<pre>[1,1,2,3,5,8,13,21,34,55]
f1 = 4506699633677819813104383235728886049367860596218604830803023149600030645708721396248792609141030396244873266580345011219530209367425581019871067646094200262285202346655868899711089246778413354004103631553925405243</pre>

===Array===
<syntaxhighlight lang="picat">fib_array(0,[0]).
fib_array(1,[0,1]).
fib_array(N,A) :-
N > 1,
A = new_array(N),
A[1] = 1,
A[2] = 1,
foreach(I in 3..N)
A[I] = A[I-1] + A[I-2]
end.</syntaxhighlight>

===Loop===
<syntaxhighlight lang="picat">fib_loop(N) = Curr =>
Curr = 0,
Prev = 1,
foreach(_I in 1..N)
Tmp = Curr,
Curr := Curr + Prev,
Prev := Tmp
end.</syntaxhighlight>

===Formula===
{{trans|Tcl}}
Works for n <= 70.
<syntaxhighlight lang="picat">fib_formula(N) = round((0.5 + 0.5*sqrt(5))**N / sqrt(5)).</syntaxhighlight>

==="Lazy lists"===
{{trans|Prolog}}
<syntaxhighlight lang="picat">go =>fib_lazy(X),
A = new_list(15),
append(A,_,X),
println(A),

fib_lazy([0,1|X]) :-
ffib(0,1,X).
ffib(A,B,X) :-
freeze(X, (C is A+B, X=[C|Y], ffib(B,C,Y)) ).</syntaxhighlight>

{{out}}
<pre>[0,1,1,2,3,5,8,13,21,34,55,89,144,233,377]</pre>

===Generators idiom===
{{trans|Prolog}}
<syntaxhighlight lang="picat">go =>
take(15, $fib_gen(0,1), $T-[], _G),
println(T).

take( 0, Next, Z-Z, Next).
take( N, Next, [A|B]-Z, NZ):- N>0, !, next( Next, A, Next1),
N1 is N-1,
take( N1, Next1, $B-Z, NZ).
next( fib_gen(A,B), A, fib_gen(B,C)):- C is A+B.</syntaxhighlight>

{{out}}
<pre>[0,1,1,2,3,5,8,13,21,34,55,89,144,233,377]</pre>

===Reversible===
This is a reversible variant using constraint modelling.

<code>fib_rev(N,F)</code> has these two usages:
* find F given a value N (this is the normal usage)
* find N given a value F (backward usage)


Note: In general, Picat supports arbitrary precision for integers. However, the constraint solvers only supports integer domains of -2**56..2**56 so the largest Fibonacci number that can be found by this predicate is N = 81.


<syntaxhighlight lang="picat">import cp.

go =>
N1 = 30,
fib_rev(30,F1),
println([n1=N1,fib1=F1]),
F2 #= 20365011074,
fib_rev(N2,F2),
println([n2=N2,f2=F2]),
F3 = 61305790721611591,
fib_rev(N3,F3),
println([n3=N3,F3]),
nl.

table
fib_rev(0,1).
fib_rev(1,1).
fib_rev(N,F) :-
N #> 0,
F #> 0,
N1 #= N-1,
N2 #= N-2,
fib_rev(N1,F1),
fib_rev(N2,F2),
F #= F1+F2.</syntaxhighlight>

{{out}}
<pre>[n1 = 30,fib1 = 1346269]
[n2 = 50,f2 = 20365011074]
[n3 = 81,61305790721611591]</pre>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
===Recursive===
===Recursive===
<lang PicoLisp>(de fibo (N)
<syntaxhighlight lang="picolisp">(de fibo (N)
(if (>= 2 N)
(if (>= 2 N)
1
1
(+ (fibo (dec N)) (fibo (- N 2))) ) )</lang>
(+ (fibo (dec N)) (fibo (- N 2))) ) )</syntaxhighlight>





===Recursive with Cache===
===Recursive with Cache===
Using a recursive version doesn't need to be slow, as the following shows:
Using a recursive version doesn't need to be slow, as the following shows:
<lang PicoLisp>(de fibo (N)
<syntaxhighlight lang="picolisp">(de fibo (N)
(cache '(NIL) N # Use a cache to accelerate
(cache '(NIL) N # Use a cache to accelerate
(if (>= 2 N)
(if (>= 2 N)
Line 7,270: Line 11,065:
(+ (fibo (dec N)) (fibo (- N 2))) ) ) )
(+ (fibo (dec N)) (fibo (- N 2))) ) ) )


(bench (fibo 1000))</lang>
(bench (fibo 1000))</syntaxhighlight>
Output:
Output:
<lang PicoLisp>0.012 sec
<syntaxhighlight lang="picolisp">0.012 sec
-> 43466557686937456435688527675040625802564660517371780402481729089536555417949
-> 43466557686937456435688527675040625802564660517371780402481729089536555417949
05189040387984007925516929592259308032263477520968962323987332247116164299644090
05189040387984007925516929592259308032263477520968962323987332247116164299644090
6533187938298969649928516003704476137795166849228875</lang>
6533187938298969649928516003704476137795166849228875</syntaxhighlight>


===Iterative===
===Iterative===
<lang PicoLisp>(de fib (N)
<syntaxhighlight lang="picolisp">(de fib (N)
(let (A 0 B 1)
(let (A 0 B 1)
(do N
(do N
(prog1 B (setq B (+ A B) A @)) ) ) )</lang>
(prog1 B (setq B (+ A B) A @)) ) ) )</syntaxhighlight>


===Coroutines===
===Coroutines===
<lang PicoLisp>(co 'fibo
<syntaxhighlight lang="picolisp">(co 'fibo
(let (A 0 B 1)
(let (A 0 B 1)
(yield 'ready)
(yield 'ready)
Line 7,294: Line 11,089:
(printsp (yield 'next 'fibo)) )
(printsp (yield 'next 'fibo)) )
(prinl)
(prinl)
(yield NIL 'fibo)</lang>
(yield NIL 'fibo)</syntaxhighlight>
{{out}}
{{out}}
<pre>1 1 2 3 5 8 13 21 34 55 89 144 233 377 610</pre>
<pre>1 1 2 3 5 8 13 21 34 55 89 144 233 377 610</pre>

=={{header|Pike}}==

===Iterative===
<syntaxhighlight lang="pike">int
fibIter(int n) {
int fibPrev, fib, i;
if (n < 2) {
return 1;
}
fibPrev = 0;
fib = 1;
for (i = 1; i < n; i++) {
int oldFib = fib;
fib += fibPrev;
fibPrev = oldFib;
}
return fib;
}</syntaxhighlight>

===Recursive===
<syntaxhighlight lang="pike">int
fibRec(int n) {
if (n < 2) {
return(1);
}
return( fib(n-2) + fib(n-1) );
}</syntaxhighlight>


=={{header|PIR}}==
=={{header|PIR}}==
Recursive:
Recursive:
{{works with|Parrot|tested with 2.4.0}}
{{works with|Parrot|tested with 2.4.0}}
<lang pir>.sub fib
<syntaxhighlight lang="pir">.sub fib
.param int n
.param int n
.local int nt
.local int nt
Line 7,330: Line 11,153:
DONE:
DONE:
end
end
.end</lang>
.end</syntaxhighlight>


Iterative (stack-based):
Iterative (stack-based):
{{works with|Parrot|tested with 2.4.0}}
{{works with|Parrot|tested with 2.4.0}}
<lang pir>.sub fib
<syntaxhighlight lang="pir">.sub fib
.param int n
.param int n
.local int counter
.local int counter
Line 7,383: Line 11,206:
DONE:
DONE:
end
end
.end</lang>
.end</syntaxhighlight>


=={{header|Pike}}==
=={{header|PL/0}}==
The program waits for ''n''. Then it displays ''n''<sup>th</sup> Fibonacci number.
<syntaxhighlight lang="pascal">
var n, a, b, i, tmp;
begin
? n;
a := 0; b := 1;
i := 2;
while i <= n do
begin
tmp := b; b := a + b; a := tmp;
i := i + 1
end;
! b
end.
</syntaxhighlight>
4 runs.
{{in}}
<pre>5</pre>
{{out}}
<pre> 5</pre>
{{in}}
<pre>9</pre>
{{out}}
<pre> 34</pre>
{{in}}
<pre>13</pre>
{{out}}
<pre> 233</pre>
{{in}}
<pre>20</pre>
{{out}}
<pre> 6765</pre>


===Iterative===
=={{header|PL/I}}==
<syntaxhighlight lang="pli">/* Form the n-th Fibonacci number, n > 1. 12 March 2022 */
<lang pike>int
Fib: procedure (n) returns (fixed binary (31));
fibIter(int n) {
declare (i, n, f1, f2, f3) fixed binary (31);
int fibPrev, fib, i;
if (n < 2) {
return 1;
}
fibPrev = 0;
fib = 1;
for (i = 1; i < n; i++) {
int oldFib = fib;
fib += fibPrev;
fibPrev = oldFib;
}
return fib;
}</lang>


f1 = 0; f2 = 1;
===Recursive===
do i = 1 to n-2;
<lang pike>int
f3 = f1 + f2;
fibRec(int n) {
if (n < 2) {
f1 = f2;
return(1);
f2 = f3;
}
end;
return( fib(n-2) + fib(n-1) );
return (f3);
}</lang>


end Fib;
=={{header|PL/I}}==
</syntaxhighlight>
<lang pli>/* Form the n-th Fibonacci number, n > 1. */

get list(n);
=={{header|PL/M}}==
f1 = 0; f2 = 1;
<syntaxhighlight lang="plm">100H:
do i = 2 to n;
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
f3 = f1 + f2;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
put skip edit('fibo(',i,')=',f3)(a,f(5),a,f(5));
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
f1 = f2;

f2 = f3;
PRINT$NUMBER: PROCEDURE (N);
end;</lang>
DECLARE S (6) BYTE INITIAL ('.....$');
DECLARE (N, P) ADDRESS, C BASED P BYTE;
P = .S(5);
DIGIT:
P = P - 1;
C = N MOD 10 + '0';
N = N / 10;
IF N > 0 THEN GO TO DIGIT;
CALL PRINT(P);
END PRINT$NUMBER;

FIBONACCI: PROCEDURE (N) ADDRESS;
DECLARE (N, A, B, C, I) ADDRESS;
IF N<=1 THEN RETURN N;
A = 0;
B = 1;
DO I=2 TO N;
C = A;
A = B;
B = A + C;
END;
RETURN B;
END FIBONACCI;

DECLARE I ADDRESS;
DO I=0 TO 20;
CALL PRINT$NUMBER(FIBONACCI(I));
CALL PRINT(.' $');
END;
CALL EXIT;
EOF</syntaxhighlight>
{{out}}
<pre>0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765</pre>

=={{header|PL/pgSQL}}==

=== Recursive ===
<syntaxhighlight lang="sql">CREATE OR REPLACE FUNCTION fib(n INTEGER) RETURNS INTEGER AS $$
BEGIN
IF (n < 2) THEN
RETURN n;
END IF;
RETURN fib(n - 1) + fib(n - 2);
END;
$$ LANGUAGE plpgsql;</syntaxhighlight>

=== Calculated ===
<syntaxhighlight lang="sql">CREATE OR REPLACE FUNCTION fibFormula(n INTEGER) RETURNS INTEGER AS $$
BEGIN
RETURN round(pow((pow(5, .5) + 1) / 2, n) / pow(5, .5));
END;
$$ LANGUAGE plpgsql;</syntaxhighlight>

=== Linear ===
<syntaxhighlight lang="sql">CREATE OR REPLACE FUNCTION fibLinear(n INTEGER) RETURNS INTEGER AS $$
DECLARE
prevFib INTEGER := 0;
fib INTEGER := 1;
BEGIN
IF (n < 2) THEN
RETURN n;
END IF;

WHILE n > 1 LOOP
SELECT fib, prevFib + fib INTO prevFib, fib;
n := n - 1;
END LOOP;

RETURN fib;
END;
$$ LANGUAGE plpgsql;</syntaxhighlight>

=== Tail recursive ===
<syntaxhighlight lang="sql">CREATE OR REPLACE FUNCTION fibTailRecursive(n INTEGER, prevFib INTEGER DEFAULT 0, fib INTEGER DEFAULT 1)
RETURNS INTEGER AS $$
BEGIN
IF (n = 0) THEN
RETURN prevFib;
END IF;
RETURN fibTailRecursive(n - 1, fib, prevFib + fib);
END;
$$ LANGUAGE plpgsql;</syntaxhighlight>


=={{header|PL/SQL}}==
=={{header|PL/SQL}}==
<syntaxhighlight lang="plsql">
<lang PL/SQL>Create or replace Function fnu_fibonnaci(p_iNumber integer)
create or replace function fnu_fibonacci(p_num integer) return integer is
return integer
f integer;
is
nuFib integer;
p integer;
nuP integer;
q integer;
begin
nuQ integer;
case when p_num < 0 or p_num != trunc(p_num)
Begin
then raise_application_error(-20001, 'Invalid input: ' || p_num, true);
if p_iNumber is not null then
if p_iNumber=0 then
when p_num in (0, 1) then f := p_num;
nuFib:=0;
else
Elsif p_iNumber=1 then
p := 0;
nuFib:=1;
q := 1;
for i in 2 .. p_num loop
Else
nuP:=0;
f := p + q;
nuQ:=1;
p := q;
For nuI in 2..p_iNumber loop
q := f;
nuFib:=nuP+nuQ;
end loop;
end case;
nuP:=nuQ;
return(f);
nuQ:=nuFib;
end fnu_fibonacci;
End loop;
/
End if;
</syntaxhighlight>
End if;

return(nuFib);
=={{header|Plain English}}==
End fnu_fibonnaci;</lang>
<syntaxhighlight lang="plainenglish">To find a fibonacci number given a count:
Put 0 into a number.
Put 1 into another number.
Loop.
If a counter is past the count, put the number into the fibonacci number; exit.
Add the number to the other number.
Swap the number with the other number.
Repeat.</syntaxhighlight>


=={{header|Pop11}}==
=={{header|Pop11}}==
<lang pop11>define fib(x);
<syntaxhighlight lang="pop11">define fib(x);
lvars a , b;
lvars a , b;
1 -> a;
1 -> a;
Line 7,459: Line 11,391:
endrepeat;
endrepeat;
a;
a;
enddefine;</lang>
enddefine;</syntaxhighlight>


=={{header|PostScript}}==
=={{header|PostScript}}==
Enter the desired number for "n" and run through your favorite postscript previewer or send to your postscript printer:
Enter the desired number for "n" and run through your favorite postscript previewer or send to your postscript printer:


<lang postscript>%!PS
<syntaxhighlight lang="postscript">%!PS


% We want the 'n'th fibonacci number
% We want the 'n'th fibonacci number
Line 7,483: Line 11,415:
(Fib\() show n (....) cvs show (\)=) show n fib (.....) cvs show
(Fib\() show n (....) cvs show (\)=) show n fib (.....) cvs show


showpage</lang>
showpage</syntaxhighlight>


=={{header|Potion}}==
=={{header|Potion}}==
Line 7,489: Line 11,421:
===Recursive===
===Recursive===
Starts with int and upgrades on-the-fly to doubles.
Starts with int and upgrades on-the-fly to doubles.
<lang potion>recursive = (n):
<syntaxhighlight lang="potion">recursive = (n):
if (n <= 1): 1. else: recursive (n - 1) + recursive (n - 2)..
if (n <= 1): 1. else: recursive (n - 1) + recursive (n - 2)..


n = 40
n = 40
("fib(", n, ")= ", recursive (n), "\n") join print</lang>
("fib(", n, ")= ", recursive (n), "\n") join print</syntaxhighlight>


<pre>
<pre>
Line 7,501: Line 11,433:


===Iterative===
===Iterative===
<lang potion>iterative = (n) :
<syntaxhighlight lang="potion">iterative = (n) :
curr = 0
curr = 0
prev = 1
prev = 1
Line 7,511: Line 11,443:
.
.
curr
curr
.</lang>
.</syntaxhighlight>


===Matrix based===
===Matrix based===
<lang potion>sqr = (x): x * x.
<syntaxhighlight lang="potion">sqr = (x): x * x.


# Based on the fact that
# Based on the fact that
Line 7,533: Line 11,465:
.
.
algorithm(n)(0)
algorithm(n)(0)
.</lang>
.</syntaxhighlight>


===Handling negative values===
===Handling negative values===
<lang>fibonacci = (n) :
<syntaxhighlight lang="text">fibonacci = (n) :
myFavorite = matrix
myFavorite = matrix
if (n >= 0) :
if (n >= 0) :
Line 7,548: Line 11,480:
.
.
.
.
.</lang>
.</syntaxhighlight>

=={{header|PowerBASIC}}==
{{trans|BASIC}}

There seems to be a limitation (dare I say, bug?) in PowerBASIC regarding how large numbers are stored. 10E17 and larger get rounded to the nearest 10. For F(n), where ABS(n) > 87, is affected like this:
actual: displayed:
F(88) 1100087778366101931 1100087778366101930
F(89) 1779979416004714189 1779979416004714190
F(90) 2880067194370816120 2880067194370816120
F(91) 4660046610375530309 4660046610375530310
F(92) 7540113804746346429 7540113804746346430

<lang powerbasic>FUNCTION fibonacci (n AS LONG) AS QUAD
DIM u AS LONG, a AS LONG, L0 AS LONG, outP AS QUAD
STATIC fibNum() AS QUAD

u = UBOUND(fibNum)
a = ABS(n)

IF u < 1 THEN
REDIM fibNum(1)
fibNum(1) = 1
u = 1
END IF

SELECT CASE a
CASE 0 TO 92
IF a > u THEN
REDIM PRESERVE fibNum(a)
FOR L0 = u + 1 TO a
fibNum(L0) = fibNum(L0 - 1) + fibNum(L0 - 2)
IF 88 = L0 THEN fibNum(88) = fibNum(88) + 1
NEXT
END IF
IF n < 0 THEN
fibonacci = fibNum(a) * ((-1)^(a+1))
ELSE
fibonacci = fibNum(a)
END IF
CASE ELSE
'Even without the above-mentioned bug, we're still limited to
'F(+/-92), due to data type limits. (F(93) = &hA94F AD42 221F 2702)
ERROR 6
END SELECT
END FUNCTION

FUNCTION PBMAIN () AS LONG
DIM n AS LONG
#IF NOT %DEF(%PB_CC32)
OPEN "out.txt" FOR OUTPUT AS 1
#ENDIF
FOR n = -92 TO 92
#IF %DEF(%PB_CC32)
PRINT STR$(n); ": "; FORMAT$(fibonacci(n), "#")
#ELSE
PRINT #1, STR$(n) & ": " & FORMAT$(fibonacci(n), "#")
#ENDIF
NEXT
CLOSE
END FUNCTION</lang>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
===Iterative===
===Iterative===
<lang powershell>
<syntaxhighlight lang="powershell">
function FibonacciNumber ( $count )
function FibonacciNumber ( $count )
{
{
Line 7,622: Line 11,494:
return $answer
return $answer
}
}
</syntaxhighlight>
</lang>


An even shorter version that eschews function calls altogether:
An even shorter version that eschews function calls altogether:


<lang powershell>
<syntaxhighlight lang="powershell">
$count = 8
$count = 8
$answer = @(0,1)
$answer = @(0,1)
0..($count - $answer.Length) | Foreach { $answer += $answer[-1] + $answer[-2] }
0..($count - $answer.Length) | Foreach { $answer += $answer[-1] + $answer[-2] }
$answer
$answer
</syntaxhighlight>
</lang>


===Recursive===
===Recursive===
<lang powershell>function fib($n) {
<syntaxhighlight lang="powershell">function fib($n) {
switch ($n) {
switch ($n) {
0 { return 0 }
0 { return 0 }
Line 7,641: Line 11,513:
default { return (fib ($n - 1)) + (fib ($n - 2)) }
default { return (fib ($n - 1)) + (fib ($n - 2)) }
}
}
}</lang>
}</syntaxhighlight>

=={{header|Processing}}==
{{trans|Java}}
<syntaxhighlight lang="processing">void setup() {
size(400, 400);
fill(255, 64);
frameRate(2);
}
void draw() {
int num = fibonacciNum(frameCount);
println(frameCount, num);
rect(0,0,num, num);
if(frameCount==14) frameCount = -1; // restart
}
int fibonacciNum(int n) {
return (n < 2) ? n : fibonacciNum(n - 1) + fibonacciNum(n - 2);
}</syntaxhighlight>

On the nth frame, the nth Fibonacci number is printed to the console and a square of that size is drawn on the sketch surface. The sketch restarts to keep drawing within the window size.

{{out}}
<pre>1
1
2
3
5
8
13
21
34
55
89
144
233
377</pre>


=={{header|Prolog}}==
=={{header|Prolog}}==
Line 7,647: Line 11,554:
{{works with|GNU Prolog}}
{{works with|GNU Prolog}}
{{works with|YAP}}
{{works with|YAP}}
<lang prolog>
<syntaxhighlight lang="prolog">
fib(1, 1) :- !.
fib(1, 1) :- !.
fib(0, 0) :- !.
fib(0, 0) :- !.
Line 7,654: Line 11,561:
B is N - 2, fib(B, B1),
B is N - 2, fib(B, B1),
Value is A1 + B1.
Value is A1 + B1.
</syntaxhighlight>
</lang>


This naive implementation works, but is very slow for larger values of N. Here are some simple measurements (in SWI-Prolog):
This naive implementation works, but is very slow for larger values of N. Here are some simple measurements (in SWI-Prolog):
<lang prolog>?- time(fib(0,F)).
<syntaxhighlight lang="prolog">?- time(fib(0,F)).
% 2 inferences, 0.000 CPU in 0.000 seconds (88% CPU, 161943 Lips)
% 2 inferences, 0.000 CPU in 0.000 seconds (88% CPU, 161943 Lips)
F = 0.
F = 0.
Line 7,675: Line 11,582:
?- time(fib(40,F)).
?- time(fib(40,F)).
% 496,740,421 inferences, 138.705 CPU in 140.206 seconds (99% CPU, 3581264 Lips)
% 496,740,421 inferences, 138.705 CPU in 140.206 seconds (99% CPU, 3581264 Lips)
F = 102334155.</lang>
F = 102334155.</syntaxhighlight>


As you can see, the calculation time goes up exponentially as N goes higher.
As you can see, the calculation time goes up exponentially as N goes higher.
Line 7,685: Line 11,592:


The performance problem can be readily fixed by the addition of two lines of code (the first and last in this version):
The performance problem can be readily fixed by the addition of two lines of code (the first and last in this version):
<lang prolog>%:- dynamic fib/2. % This is ISO, but GNU doesn't like it.
<syntaxhighlight lang="prolog">%:- dynamic fib/2. % This is ISO, but GNU doesn't like it.
:- dynamic(fib/2). % Not ISO, but works in SWI, YAP and GNU unlike the ISO declaration.
:- dynamic(fib/2). % Not ISO, but works in SWI, YAP and GNU unlike the ISO declaration.
fib(1, 1) :- !.
fib(1, 1) :- !.
Line 7,693: Line 11,600:
B is N - 2, fib(B, B1),
B is N - 2, fib(B, B1),
Value is A1 + B1,
Value is A1 + B1,
asserta((fib(N, Value) :- !)).</lang>
asserta((fib(N, Value) :- !)).</syntaxhighlight>


Let's take a look at the execution costs now:
Let's take a look at the execution costs now:


<lang prolog>?- time(fib(0,F)).
<syntaxhighlight lang="prolog">?- time(fib(0,F)).
% 2 inferences, 0.000 CPU in 0.000 seconds (90% CPU, 160591 Lips)
% 2 inferences, 0.000 CPU in 0.000 seconds (90% CPU, 160591 Lips)
F = 0.
F = 0.
Line 7,715: Line 11,622:
?- time(fib(40,F)).
?- time(fib(40,F)).
% 41 inferences, 0.000 CPU in 0.000 seconds (96% CPU, 543572 Lips)
% 41 inferences, 0.000 CPU in 0.000 seconds (96% CPU, 543572 Lips)
F = 102334155.</lang>
F = 102334155.</syntaxhighlight>


In this case by asserting the new N,Value pairing as a rule in the database we're making the classic time/space tradeoff. Since the space costs are (roughly) linear by N and the time costs are exponential by N, the trade-off is desirable. You can see the poor man's memoizing easily:
In this case by asserting the new N,Value pairing as a rule in the database we're making the classic time/space tradeoff. Since the space costs are (roughly) linear by N and the time costs are exponential by N, the trade-off is desirable. You can see the poor man's memoizing easily:


<lang prolog>?- listing(fib).
<syntaxhighlight lang="prolog">?- listing(fib).
:- dynamic fib/2.
:- dynamic fib/2.


Line 7,769: Line 11,676:
fib(C, F),
fib(C, F),
D is E+F,
D is E+F,
asserta((fib(A, D):-!)).</lang>
asserta((fib(A, D):-!)).</syntaxhighlight>


All of the interim N/Value pairs have been asserted as facts for quicker future use, speeding up the generation of the higher Fibonacci numbers.
All of the interim N/Value pairs have been asserted as facts for quicker future use, speeding up the generation of the higher Fibonacci numbers.
Line 7,775: Line 11,682:
===Continuation passing style===
===Continuation passing style===
Works with <b>SWI-Prolog</b> and module lambda, written by <b>Ulrich Neumerkel</b> found there http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl
Works with <b>SWI-Prolog</b> and module lambda, written by <b>Ulrich Neumerkel</b> found there http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl
<lang Prolog>:- use_module(lambda).
<syntaxhighlight lang="prolog">:- use_module(lambda).
fib(N, FN) :-
fib(N, FN) :-
cont_fib(N, _, FN, \_^Y^_^U^(U = Y)).
cont_fib(N, _, FN, \_^Y^_^U^(U = Y)).
Line 7,788: Line 11,695:
call(Pred, FNA, FNB, FN1, FN)
call(Pred, FNA, FNB, FN1, FN)
).
).
</syntaxhighlight>
</lang>


===With lazy lists===
===With lazy lists===
Works with <b>SWI-Prolog</b> and others that support <code>freeze/2</code>.
Works with <b>SWI-Prolog</b> and others that support <code>freeze/2</code>.


<lang Prolog>fib([0,1|X]) :-
<syntaxhighlight lang="prolog">fib([0,1|X]) :-
ffib(0,1,X).
ffib(0,1,X).
ffib(A,B,X) :-
ffib(A,B,X) :-
freeze(X, (C is A+B, X=[C|Y], ffib(B,C,Y)) ).</lang>
freeze(X, (C is A+B, X=[C|Y], ffib(B,C,Y)) ).</syntaxhighlight>


The predicate <code>fib(Xs)</code> unifies <code>Xs</code> with an infinite list whose values are the Fibonacci sequence. The list can be used like this:
The predicate <code>fib(Xs)</code> unifies <code>Xs</code> with an infinite list whose values are the Fibonacci sequence. The list can be used like this:


<lang Prolog>?- fib(X), length(A,15), append(A,_,X), writeln(A).
<syntaxhighlight lang="prolog">?- fib(X), length(A,15), append(A,_,X), writeln(A).
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]</lang>
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]</syntaxhighlight>


===Generators idiom===
===Generators idiom===


<lang Prolog>take( 0, Next, Z-Z, Next).
<syntaxhighlight lang="prolog">take( 0, Next, Z-Z, Next).
take( N, Next, [A|B]-Z, NZ):- N>0, !, next( Next, A, Next1),
take( N, Next, [A|B]-Z, NZ):- N>0, !, next( Next, A, Next1),
N1 is N-1,
N1 is N-1,
Line 7,814: Line 11,721:
%% usage: ?- take(15, fib(0,1), _X-[], G), writeln(_X).
%% usage: ?- take(15, fib(0,1), _X-[], G), writeln(_X).
%% [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
%% [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
%% G = fib(610, 987)</lang>
%% G = fib(610, 987)</syntaxhighlight>


=== Yet another implementation ===
=== Yet another implementation ===
One of my favorites; loosely similar to the first example, but without the performance penalty, and needs nothing special to implement. Not even a dynamic database predicate. Attributed to M.E. for the moment, but simply because I didn't bother to search for the many people who probably did it like this long before I did. If someone knows who came up with it first, please let us know.
One of my favorites; loosely similar to the first example, but without the performance penalty, and needs nothing special to implement. Not even a dynamic database predicate. Attributed to M.E. for the moment, but simply because I didn't bother to search for the many people who probably did it like this long before I did. If someone knows who came up with it first, please let us know.


<lang Prolog>% Fibonacci sequence generator
<syntaxhighlight lang="prolog">% Fibonacci sequence generator
fib(C, [P,S], C, N) :- N is P + S.
fib(C, [P,S], C, N) :- N is P + S.
fib(C, [P,S], Cv, V) :- succ(C, Cn), N is P + S, !, fib(Cn, [S,N], Cv, V).
fib(C, [P,S], Cv, V) :- succ(C, Cn), N is P + S, !, fib(Cn, [S,N], Cv, V).
Line 7,825: Line 11,732:
fib(0, 0).
fib(0, 0).
fib(1, 1).
fib(1, 1).
fib(C, N) :- fib(2, [0,1], C, N). % Generate from 3rd sequence on</lang>
fib(C, N) :- fib(2, [0,1], C, N). % Generate from 3rd sequence on</syntaxhighlight>
Looking at performance:
Looking at performance:
<pre> ?- time(fib(30,X)).
<pre> ?- time(fib(30,X)).
Line 7,868: Line 11,775:
X = 100 .</pre>
X = 100 .</pre>


=== Efficient implementation ===
=={{header|Pure}}==
<syntaxhighlight lang="prolog">
===Tail Recursive===
% John Devou: 26-Nov-2021
<lang pure>fib n = loop 0 1 n with
% Efficient program to calculate n-th Fibonacci number.
loop a b n = if n==0 then a else loop b (a+b) (n-1);
% Works fast for n ≤ 1 000 000 000.
end;</lang>


b(0,Bs,Bs).
=={{header|PureBasic}}==
b(N,Bs,Res):- N > 0, B is mod(N,2), M is div(N,2), b(M,[B|Bs],Res).


f([],A,_,_,A).
===Macro based calculation===
f([X|Xs],A,B,C,Res):- AA is A^2, BB is B^2, A_ is 2*BB-3*AA-C, B_ is AA+BB,
<lang PureBasic>Macro Fibonacci (n)
(X =:= 1 -> T is A_+B_, f(Xs,B_,T,-2,Res); f(Xs,A_,B_,2,Res)).
Int((Pow(((1+Sqr(5))/2),n)-Pow(((1-Sqr(5))/2),n))/Sqr(5))
EndMacro</lang>
===Recursive===
<lang PureBasic>Procedure FibonacciReq(n)
If n<2
ProcedureReturn n
Else
ProcedureReturn FibonacciReq(n-1)+FibonacciReq(n-2)
EndIf
EndProcedure</lang>


fib(N,F):- b(N,[],Bs), f(Bs,0,1,2,F), !.
===Recursive & optimized with a static hash table===
</syntaxhighlight>
This will be much faster on larger n's, this as it uses a table to store known parts instead of recalculating them.
{{out}}
On my machine the speedup compares to above code is
<pre>
Fib(n) Speedup
?- time(fib(30,X)).
20 2
% 59 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)
25 23
X = 832040.
30 217
40 25847
46 1156741
<lang PureBasic>Procedure Fibonacci(n)
Static NewMap Fib.i()
Protected FirstRecursion
If MapSize(Fib())= 0 ; Init the hash table the first run
Fib("0")=0: Fib("1")=1
FirstRecursion = #True
EndIf
If n >= 2
Protected.s s=Str(n)
If Not FindMapElement(Fib(),s) ; Calculate only needed parts
Fib(s)= Fibonacci(n-1)+Fibonacci(n-2)
EndIf
n = Fib(s)
EndIf
If FirstRecursion ; Free the memory when finalizing the first call
ClearMap(Fib())
EndIf
ProcedureReturn n
EndProcedure</lang>


?- time(fib(100,X)).
'''Example'''
% 80 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)
Fibonacci(0)= 0
X = 354224848179261915075.
Fibonacci(1)= 1

Fibonacci(2)= 1
?- time(fib(500,X)).
Fibonacci(3)= 2
% 102 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)
Fibonacci(4)= 3
X = 139423224561697880139724382870407283950070256587697307264108962948325571622863290691557658876222521294125.
Fibonacci(5)= 5

?- time(fib(1000000000,_)).
FibonacciReq(0)= 0
% 334 inferences, 7.078 CPU in 7.526 seconds (94% CPU, 47 Lips)
FibonacciReq(1)= 1
true.
FibonacciReq(2)= 1
</pre>
FibonacciReq(3)= 2

FibonacciReq(4)= 3
=={{header|Pure}}==
FibonacciReq(5)= 5
===Tail Recursive===
<syntaxhighlight lang="pure">fib n = loop 0 1 n with
loop a b n = if n==0 then a else loop b (a+b) (n-1);
end;</syntaxhighlight>


=={{header|Purity}}==
=={{header|Purity}}==
The following takes a natural number and generates an initial segment of the Fibonacci sequence of that length:
The following takes a natural number and generates an initial segment of the Fibonacci sequence of that length:


<syntaxhighlight lang="purity">
<lang Purity>
data Fib1 = FoldNat
data Fib1 = FoldNat
<
<
Line 7,944: Line 11,824:
(uncurry Cons) . ((uncurry Add) . (Head, Head . Tail), id)
(uncurry Cons) . ((uncurry Add) . (Head, Head . Tail), id)
>
>
</syntaxhighlight>
</lang>


This following calculates the Fibonacci sequence as an infinite stream of natural numbers:
This following calculates the Fibonacci sequence as an infinite stream of natural numbers:


<syntaxhighlight lang="purity">
<lang Purity>
type (Stream A?,,,Unfold) = gfix X. A? . X?
type (Stream A?,,,Unfold) = gfix X. A? . X?
data Fib2 = Unfold ((outl, (uncurry Add, outl))) ((curry id) One One)
data Fib2 = Unfold ((outl, (uncurry Add, outl))) ((curry id) One One)
</syntaxhighlight>
</lang>


As a histomorphism:
As a histomorphism:


<syntaxhighlight lang="purity">
<lang Purity>
import Histo
import Histo


Line 7,967: Line 11,847:
> (outr $p1)) . UnmakeCofree
> (outr $p1)) . UnmakeCofree
>
>
</syntaxhighlight>
</lang>


=={{header|Python}}==
=={{header|Python}}==
===Iterative positive and negative===
<lang python>def fib(n,x=[0,1]):
for i in range(abs(n)-1): x=[x[1],sum(x)]
return x[1]*pow(-1,abs(n)-1) if n<0 else x[1] if n else 0

for i in range(-30,31): print fib(i),</lang>
Output:
<pre>
-832040 514229 -317811 196418 -121393 75025 -46368 28657 -17711 10946 -6765 4181 -2584 1597 -987
610 -377 233 -144 89 -55 34 -21 13 -8 5 -3 2 -1 1 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040
</pre>
===Analytic===
===Analytic===
Binet's formula:
Binet's formula:
<lang python>from math import *
<syntaxhighlight lang="python">from math import *


def analytic_fibonacci(n):
def analytic_fibonacci(n):
Line 7,993: Line 11,861:


for i in range(1,31):
for i in range(1,31):
print analytic_fibonacci(i),</lang>
print analytic_fibonacci(i),</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 8,000: Line 11,868:


===Iterative===
===Iterative===
<lang python>def fibIter(n):
<syntaxhighlight lang="python">def fibIter(n):
if n < 2:
if n < 2:
return n
return n
fibPrev = 1
fibPrev = 1
fib = 1
fib = 1
for num in xrange(2, n):
for _ in range(2, n):
fibPrev, fib = fib, fib + fibPrev
fibPrev, fib = fib, fib + fibPrev
return fib</lang>
return fib</syntaxhighlight>

====Iterative positive and negative====
<syntaxhighlight lang="python">def fib(n,x=[0,1]):
for i in range(abs(n)-1): x=[x[1],sum(x)]
return x[1]*pow(-1,abs(n)-1) if n<0 else x[1] if n else 0

for i in range(-30,31): print fib(i),</syntaxhighlight>
Output:
<pre>
-832040 514229 -317811 196418 -121393 75025 -46368 28657 -17711 10946 -6765 4181 -2584 1597 -987
610 -377 233 -144 89 -55 34 -21 13 -8 5 -3 2 -1 1 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040
</pre>

===Recursive===
===Recursive===
<lang python>def fibRec(n):
<syntaxhighlight lang="python">def fibRec(n):
if n < 2:
if n < 2:
return n
return n
else:
else:
return fibRec(n-1) + fibRec(n-2)</lang>
return fibRec(n-1) + fibRec(n-2)</syntaxhighlight>


===Recursive with Memoization===
===Recursive with Memoization===


<lang python>def fibMemo():
<syntaxhighlight lang="python">def fibMemo():
pad = {0:0, 1:1}
pad = {0:0, 1:1}
def func(n):
def func(n):
Line 8,027: Line 11,909:
fm = fibMemo()
fm = fibMemo()
for i in range(1,31):
for i in range(1,31):
print fm(i),</lang>
print fm(i),</syntaxhighlight>


Output:
Output:
<pre>
<pre>
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040</pre>
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040</pre>




===Better Recursive doesn't need Memoization===
===Better Recursive doesn't need Memoization===
Line 8,037: Line 11,921:
The recursive code as written two sections above is incredibly slow and inefficient due to the nested recursion calls. Although the memoization above makes the code run faster, it is at the cost of extra memory use. The below code is syntactically recursive but actually encodes the efficient iterative process, and thus doesn't require memoization:
The recursive code as written two sections above is incredibly slow and inefficient due to the nested recursion calls. Although the memoization above makes the code run faster, it is at the cost of extra memory use. The below code is syntactically recursive but actually encodes the efficient iterative process, and thus doesn't require memoization:


<lang python>def fibFastRec(n):
<syntaxhighlight lang="python">def fibFastRec(n):
def fib(prvprv, prv, c):
def fib(prvprv, prv, c):
if c < 1:
if c < 1:
Line 8,043: Line 11,927:
else:
else:
return fib(prv, prvprv + prv, c - 1)
return fib(prv, prvprv + prv, c - 1)
return fib(0, 1, n)</lang>
return fib(0, 1, n)</syntaxhighlight>


However, although much faster and not requiring memory, the above code can only work to a limited 'n' due to the limit on stack recursion depth by Python; it is better to use the iterative code above or the generative one below.
However, although much faster and not requiring memory, the above code can only work to a limited 'n' due to the limit on stack recursion depth by Python; it is better to use the iterative code above or the generative one below.


===Generative===
===Generative===
<lang python>def fibGen(n):
<syntaxhighlight lang="python">def fibGen(n):
a, b = 0, 1
a, b = 0, 1
while n>0:
while n>0:
yield a
yield a
a, b, n = b, a+b, n-1</lang>
a, b, n = b, a+b, n-1</syntaxhighlight>
====Example use====
====Example use====
<lang python>
<syntaxhighlight lang="python">
>>> [i for i in fibGen(11)]
>>> [i for i in fibGen(11)]


[0,1,1,2,3,5,8,13,21,34,55]
[0,1,1,2,3,5,8,13,21,34,55]
</syntaxhighlight>
</lang>


===Matrix-Based===
===Matrix-Based===
Translation of the matrix-based approach used in F#.
Translation of the matrix-based approach used in F#.
<lang python>
<syntaxhighlight lang="python">
def prevPowTwo(n):
def prevPowTwo(n):
'Gets the power of two that is less than or equal to the given input'
'Gets the power of two that is less than or equal to the given input'
Line 8,093: Line 11,977:
return q
return q
</syntaxhighlight>
</lang>


===Large step recurrence===
===Large step recurrence===
This is much faster for a single, large value of n:
This is much faster for a single, large value of n:
<lang python>def fib(n, c={0:1, 1:1}):
<syntaxhighlight lang="python">def fib(n, c={0:1, 1:1}):
if n not in c:
if n not in c:
x = n // 2
x = n // 2
Line 8,103: Line 11,987:
return c[n]
return c[n]


fib(10000000) # calculating it takes a few seconds, printing it takes eons</lang>
fib(10000000) # calculating it takes a few seconds, printing it takes eons</syntaxhighlight>


===Same as above but slightly faster===
===Same as above but slightly faster===
Putting the dictionary outside the function makes this about 2 seconds faster, could just make a wrapper:
Putting the dictionary outside the function makes this about 2 seconds faster, could just make a wrapper:
<lang python>F = {0: 0, 1: 1, 2: 1}
<syntaxhighlight lang="python">F = {0: 0, 1: 1, 2: 1}
def fib(n):
def fib(n):
if n in F:
if n in F:
Line 8,114: Line 11,998:
f2 = fib((n - 1) // 2)
f2 = fib((n - 1) // 2)
F[n] = (f1 * f1 + f2 * f2 if n & 1 else f1 * f1 - f2 * f2)
F[n] = (f1 * f1 + f2 * f2 if n & 1 else f1 * f1 - f2 * f2)
return F[n]</lang>
return F[n]</syntaxhighlight>


===Generative with Recursion===
===Generative with Recursion===
This can get very slow and uses a lot of memory. Can be sped up by caching the generator results.
This can get very slow and uses a lot of memory. Can be sped up by caching the generator results.
<lang python>def fib():
<syntaxhighlight lang="python">def fib():
"""Yield fib[n+1] + fib[n]"""
"""Yield fib[n+1] + fib[n]"""
yield 1 # have to start somewhere
yield 1 # have to start somewhere
Line 8,127: Line 12,011:


f=fib()
f=fib()
print [next(f) for _ in range(9)]</lang>
print [next(f) for _ in range(9)]</syntaxhighlight>


Output:
Output:
Line 8,133: Line 12,017:


'''Another version of recursive generators solution, starting from 0'''
'''Another version of recursive generators solution, starting from 0'''
<lang Python>from itertools import islice
<syntaxhighlight lang="python">from itertools import islice


def fib():
def fib():
Line 8,143: Line 12,027:
yield next(a)+next(b)
yield next(a)+next(b)
print(tuple(islice(fib(), 10)))</lang>
print(tuple(islice(fib(), 10)))</syntaxhighlight>

===As a scan or a fold ===
====itertools.accumulate====
The Fibonacci series can be defined quite simply and efficiently as a scan or accumulation, in which the accumulator is a pair of the two last numbers.
{{Works with|Python|3.7}}
<syntaxhighlight lang="python">'''Fibonacci accumulation'''

from itertools import accumulate, chain
from operator import add


# fibs :: Integer :: [Integer]
def fibs(n):
'''An accumulation of the first n integers in
the Fibonacci series. The accumulator is a
pair of the two preceding numbers.
'''
def go(ab, _):
return ab[1], add(*ab)

return [xy[1] for xy in accumulate(
chain(
[(0, 1)],
range(1, n)
),
go
)]


# MAIN ---
if __name__ == '__main__':
print(
'First twenty: ' + repr(
fibs(20)
)
)</syntaxhighlight>
{{Out}}
<pre>First twenty: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]</pre>

====functools.reduce====

A fold can be understood as an amnesic scan, and functools.reduce can provide a useful and efficient re-write of the scanning version above, if we only need the Nth term in the series:
{{Works with|Python|3.7}}
<syntaxhighlight lang="python">'''Nth Fibonacci term (by folding)'''

from functools import reduce
from operator import add


# nthFib :: Integer -> Integer
def nthFib(n):
'''Nth integer in the Fibonacci series.'''
def go(ab, _):
return ab[1], add(*ab)
return reduce(go, range(1, n), (0, 1))[1]


# MAIN ---
if __name__ == '__main__':
print(
'1000th term: ' + repr(
nthFib(1000)
)
)</syntaxhighlight>
{{Out}}
<pre>1000th term: 43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875</pre>

{{Works with|Python|3.9}}
<syntaxhighlight lang="python">
def fib(n):
from functools import reduce
return reduce(lambda x, y: (x[1], x[0] + x[1]), range(n), (0, 1))[0]
</syntaxhighlight>

===Array and Range===
<syntaxhighlight lang="python">fibseq = [1,1,]
fiblength = 21
for x in range(1,fiblength-1):
xcount = fibseq[x-1] + fibseq[x]
fibseq.append(xcount)
print(xcount)</syntaxhighlight>

{{Out}}
<pre>10946
</pre>

===Minimal from Russia===
<syntaxhighlight lang="python">fi1=fi2=fi3=1 # FIB Russia rextester.com/FEEJ49204
for da in range(1, 88): # Danilin
print("."*(20-len(str(fi3))), end=' ')
print(fi3)
fi3 = fi2+fi1
fi1 = fi2
fi2 = fi3</syntaxhighlight>

{{Out}}
<pre>................... 1
................... 2
................... 3

....... 6557470319842
...... 10610209857723
...... 17167680177565

.. 420196140727489673
.. 679891637638612258
. 1100087778366101931</pre>


=={{header|Qi}}==
=={{header|Qi}}==
===Recursive===
===Recursive===
<syntaxhighlight lang="qi">
<lang qi>
(define fib
(define fib
0 -> 0
0 -> 0
Line 8,153: Line 12,144:
N -> (+ (fib-r (- N 1))
N -> (+ (fib-r (- N 1))
(fib-r (- N 2))))
(fib-r (- N 2))))
</syntaxhighlight>
</lang>
===Iterative===
===Iterative===
<syntaxhighlight lang="qi">
<lang qi>
(define fib-0
(define fib-0
V2 V1 0 -> V2
V2 V1 0 -> V2
Line 8,162: Line 12,153:
(define fib
(define fib
N -> (fib-0 0 1 N))
N -> (fib-0 0 1 N))
</syntaxhighlight>
</lang>

=={{header|Quackery}}==

<syntaxhighlight lang="quackery"> [ 0 1 rot times [ tuck + ] drop ] is fibo ( n --> n )

100 fibo echo</syntaxhighlight>

{{out}}

<pre>354224848179261915075</pre>


=={{header|R}}==
=={{header|R}}==
===Iterative positive and negative===
===Iterative positive and negative===
<lang python>fib=function(n,x=c(0,1)) {
<syntaxhighlight lang="python">fib=function(n,x=c(0,1)) {
if (abs(n)>1) for (i in seq(abs(n)-1)) x=c(x[2],sum(x))
if (abs(n)>1) for (i in seq(abs(n)-1)) x=c(x[2],sum(x))
if (n<0) return(x[2]*(-1)^(abs(n)-1)) else if (n) return(x[2]) else return(0)
if (n<0) return(x[2]*(-1)^(abs(n)-1)) else if (n) return(x[2]) else return(0)
}
}


sapply(seq(-31,31),fib)</lang>
sapply(seq(-31,31),fib)</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 8,183: Line 12,184:
</pre>
</pre>
===Other methods===
===Other methods===
<lang R># recursive
<syntaxhighlight lang="r"># recursive
recfibo <- function(n) {
recfibo <- function(n) {
if ( n < 2 ) n
if ( n < 2 ) n
Line 8,221: Line 12,222:
}
}


print.table(lapply(0:20, funcfibo))</lang>
print.table(lapply(0:20, funcfibo))</syntaxhighlight>


Note that an idiomatic way to implement such low level, basic arithmethic operations in R is to implement them C and then call the compiled code.
Note that an idiomatic way to implement such low level, basic arithmethic operations in R is to implement them C and then call the compiled code.
Line 8,231: Line 12,232:


=={{header|Ra}}==
=={{header|Ra}}==
<syntaxhighlight lang="ra">
<lang Ra>
class FibonacciSequence
class FibonacciSequence
**Prints the nth fibonacci number**
**Prints the nth fibonacci number**
Line 8,277: Line 12,278:
return a
return a
</syntaxhighlight>
</lang>


=={{header|Racket}}==
=={{header|Racket}}==


===Tail Recursive===
===Tail Recursive===
<syntaxhighlight lang="racket">
<lang Racket>
(define (fib n)
(define (fib n)
(let loop ((cnt 0) (a 0) (b 1))
(let loop ((cnt 0) (a 0) (b 1))
Line 8,288: Line 12,289:
a
a
(loop (+ cnt 1) b (+ a b)))))
(loop (+ cnt 1) b (+ a b)))))
</syntaxhighlight>
</lang>


<syntaxhighlight lang="racket">
<lang Racket>
(define (fib n (a 0) (b 1))
(define (fib n (a 0) (b 1))
(if (< n 2)
(if (< n 2)
1
1
(+ a (fib (- n 1) b (+ a b)))))
(+ a (fib (- n 1) b (+ a b)))))
</syntaxhighlight>
</lang>


===Matrix Form===
===Matrix Form===
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
#lang racket


Line 8,310: Line 12,311:


(fibmat 1000)
(fibmat 1000)
</syntaxhighlight>
</lang>


===Foldl Form===
=={{header|REALbasic}}==
<syntaxhighlight lang="racket">
Pass n to this function where n is the desired number of iterations. This example uses the UInt64 datatype which is as unsigned 64 bit integer. As such, it overflows after the 93rd iteration.
(define (fib n)
<lang vb>Function fibo(n as integer) As UInt64
(car (foldl (lambda (y x)
(let ((a (car x)) (b (cdr x)))
(cons b (+ a b)))) (cons 0 1) (range n))))
</syntaxhighlight>


=={{header|Raku}}==
dim noOne as UInt64 = 1
(formerly Perl 6)
dim noTwo as UInt64 = 1
dim sum As UInt64


===List Generator===
for i as integer = 3 to n
sum = noOne + noTwo
noTwo = noOne
noOne = sum
Next


This constructs the fibonacci sequence as a lazy infinite list.
Return noOne
<syntaxhighlight lang="raku" line>constant @fib = 0, 1, *+* ... *;</syntaxhighlight>
End Function</lang>

If you really need a function for it:
<syntaxhighlight lang="raku" line>sub fib ($n) { @fib[$n] }</syntaxhighlight>

To support negative indices:
<syntaxhighlight lang="raku" line>constant @neg-fib = 0, 1, *-* ... *;
sub fib ($n) { $n >= 0 ?? @fib[$n] !! @neg-fib[-$n] }</syntaxhighlight>

===Iterative===
<syntaxhighlight lang="raku" line>sub fib (Int $n --> Int) {
$n > 1 or return $n;
my ($prev, $this) = 0, 1;
($prev, $this) = $this, $this + $prev for 1 ..^ $n;
return $this;
}</syntaxhighlight>

===Recursive===
<syntaxhighlight lang="raku" line>proto fib (Int $n --> Int) {*}
multi fib (0) { 0 }
multi fib (1) { 1 }
multi fib ($n) { fib($n - 1) + fib($n - 2) }</syntaxhighlight>

=={{header|Rapira}}==
===Iterative===
<syntaxhighlight lang="rapira">fun fibonacci(n)
if n = 0 then
return 0
fi
if n = 1 then
return 1
fi
return fibonacci(n - 1) + fibonacci(n - 2)
end</syntaxhighlight>

=={{header|RASEL}}==
<syntaxhighlight lang="text">1&-:?v2\:2\01\--2\
>$.@</syntaxhighlight>

=={{header|RATFOR}}==
<syntaxhighlight lang="RATFOR">
program Fibonacci
#
integer*4 count, loop
integer*4 num1, num2, fib

1 format(A)
2 format(I4)
3 format(I6,' ')
4 format(' ')
write(6,1,advance='no')'How Many: '
read(5,2)count

num1 = 0
num2 = 1
write(6,3,advance='no')num1
write(6,3,advance='no')num2

for (loop = 3; loop<=count; loop=loop+1)
{
fib = num1 + num2
write(6,3,advance='no')fib
num1 = num2
num2 = fib
}
write(6,4)
end
</syntaxhighlight>


=={{header|Red}}==
(unnecessarily, but pleasantly palindromic)
<syntaxhighlight lang="red">Red []

palindrome: [fn: fn-1 + fn-1: fn]
fibonacci: func [n][
fn-1: 0
fn: 1
loop n palindrome
]</syntaxhighlight>

=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
= <Prout <Repeat 18 Fibonacci 1 1>>
} ;

Repeat {
0 s.F e.X = e.X;
s.N s.F e.X = <Repeat <- s.N 1> s.F <Mu s.F e.X>>;
};

Fibonacci {
e.X s.A s.B = e.X s.A s.B <+ s.A s.B>;
};</syntaxhighlight>
{{out}}
<pre>1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765</pre>

=={{header|Relation}}==
<syntaxhighlight lang="relation">
function fibonacci (n)
if n < 2
set result = n
else
set f0 = 0
set f1 = 1
set k = 2
while k <= n
set result = f0 + f1
set f0 = f1
set f1 = result
set k = k + 1
end while
end if
end function
</syntaxhighlight>


=={{header|Retro}}==
=={{header|Retro}}==
===Recursive===
===Recursive===
<lang Retro>: fib ( n-m ) dup [ 0 = ] [ 1 = ] bi or if; [ 1- fib ] sip [ 2 - fib ] do + ;</lang>
<syntaxhighlight lang="retro">: fib ( n-m ) dup [ 0 = ] [ 1 = ] bi or if; [ 1- fib ] sip [ 2 - fib ] do + ;</syntaxhighlight>


===Iterative===
===Iterative===
<lang Retro>: fib ( n-N )
<syntaxhighlight lang="retro">: fib ( n-N )
[ 0 1 ] dip [ over + swap ] times drop ;</lang>
[ 0 1 ] dip [ over + swap ] times drop ;</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
With &nbsp; 210,000 &nbsp; numeric decimal digits, this REXX program can handle Fibonacci numbers past one million.
With &nbsp; 210,000 &nbsp; numeric decimal digits, &nbsp; this REXX program can handle Fibonacci numbers past one million.
<br>[Generally speaking, some REXX interpreters can handle up to around eight million decimal digits.]
<br>[Generally speaking, some REXX interpreters can handle up to around eight million decimal digits.]


This version of the REXX program can also handle &nbsp; ''negative'' &nbsp; Fibonacci numbers.
This version of the REXX program can also handle &nbsp; ''negative'' &nbsp; Fibonacci numbers.
<lang rexx>/*REXX program calculates the Nth Fibonacci number, N can be zero or negative. */
<syntaxhighlight lang="rexx">/*REXX program calculates the Nth Fibonacci number, N can be zero or negative. */
numeric digits 210000 /*be able to handle ginormous numbers. */
numeric digits 210000 /*be able to handle ginormous numbers. */
parse arg x y . /*allow a single number or a range. */
parse arg x y . /*allow a single number or a range. */
Line 8,364: Line 12,478:
/* [↓] an//2 [same as] (an//2==1).*/
/* [↓] an//2 [same as] (an//2==1).*/
if n>0 | an//2 then return $ /*Positive or even? Then return sum. */
if n>0 | an//2 then return $ /*Positive or even? Then return sum. */
return -$ /*Negative and odd? Return negative sum*/</lang>
return -$ /*Negative and odd? Return negative sum*/</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
{{out|output|text=&nbsp; when using the default inputs:}}
<pre style="height:63ex">
<pre style="height:150ex">
Fibonacci(-40) = -102334155
Fibonacci(-40) = -102334155
Fibonacci(-39) = 63245986
Fibonacci(-39) = 63245986
Line 8,457: Line 12,571:
Fibonacci(10000) has a length of 2090 decimal digits
Fibonacci(10000) has a length of 2090 decimal digits
</pre>
</pre>

=={{header|Rhovas}}==
Solutions support arbitrarily large numbers as Rhovas's <code>Integer</code> type is arbitrary-precision (Java <code>BigInteger</code>). Additional notes:
* <code>require num >= 0;</code> asserts input range preconditions, throwing on negative numbers

===Iterative===
Standard iterative solution using a <code>for</code> loop:
* <code>range(1, num, :incl)</code> creates an inclusive range (<code>1 <= i <= num</code>) for iteration.
** The loop uses <code>_</code> as the variable name since the value is unused.

<syntaxhighlight lang="scala">
func fibonacci(num: Integer): Integer {
require num >= 0;
var previous = 1;
var current = 0;
for (val _ in range(1, num, :incl)) {
val next = current + previous;
previous = current;
current = next;
}
return current;
}
</syntaxhighlight>

===Recursive===
Standard recursive solution using a pattern matching approach:
* <code>match</code> without arguments is a ''conditional match'', which works like <code>if/else</code> chains.
* Rhovas doesn't perform tail-call optimization yet, hence why this solution isn't tail recursive.

<syntaxhighlight lang="scala">
func fibonacci(num: Integer): Integer {
require num >= 0;
match {
num == 0: return 0;
num == 1: return 1;
else: return fibonacci(num - 1) + fibonacci(num - 2);
}
}
</syntaxhighlight>

===Negatives===
Standard solution using a pattern matching approach, delegating to an existing <code>positiveFibonacci</code> solution (as shown above). For negative fibonacci numbers, odd inputs return positive results while evens return negatives.

<syntaxhighlight lang="scala">
func fibonacci(num: Integer): Integer {
match {
num >= 0: return positiveFibonacci(num);
num.mod(2) != 0: return positiveFibonacci(-num);
else: return -positiveFibonacci(-num);
}
}
</syntaxhighlight>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
give n
give n
x = fib(n)
x = fib(n)
Line 8,467: Line 12,633:
if nr = 1 return 1 ok
if nr = 1 return 1 ok
if nr > 1 return fib(nr-1) + fib(nr-2) ok
if nr > 1 return fib(nr-1) + fib(nr-2) ok
</syntaxhighlight>
</lang>

=={{header|Rockstar}}==
===Iterative (minimized)===
<syntaxhighlight lang="rockstar">
Fibonacci takes Number
FNow is 0
FNext is 1
While FNow is less than Number
Say FNow
Put FNow into Temp
Put FNow into FNext
Put FNext plus Temp into FNext

Say Fibonacci taking 1000 (prints out highest number in Fibonacci sequence less than 1000)
</syntaxhighlight>

===Iterative (idiomatic)===
<syntaxhighlight lang="rockstar">
Love takes Time
My love was addictions
Put my love into your heart
Build it up
Until my love is as strong as Time
Whisper my love
Put my love into a river
Put your heart into my love
Put it with a river into your heart


Shout; Love taking 1000 (years, years)
</syntaxhighlight>

The semicolon and the comment <code>(years, years)</code> in this version are there only for poetic effect

===Recursive===
<syntaxhighlight lang="rockstar">
The Italian takes a lover, a kiss, a promise
love is population
hate is information
If a lover is love
Give back a kiss

If a lover is hate
Give back a promise

Knock a lover down
Put a promise with a kiss into my heart
Give back The Italian taking a lover, a promise, my heart

Listen to your heart
your mind is everything
your soul is opportunity
Whisper The Italian taking your heart, your mind, your soul
</syntaxhighlight>

=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
===Iterative===
≪ 0 1
0 4 ROLL '''START'''
OVER + SWAP
'''NEXT''' SWAP DROP
≫ '<span style="color:blue">→FIB</span>' STO
≪ { } 0 20 '''FOR''' j j <span style="color:blue">→FIB</span> + '''NEXT''' ≫ EVAL

===Recursive===
≪ '''IF''' DUP 2 > '''THEN'''
DUP 1 - <span style="color:blue">→FIB</span>
SWAP 2 - <span style="color:blue">→FIB</span> +
'''ELSE''' SIGN '''END'''
≫ '<span style="color:blue">→FIB</span>' STO

{{out}}
<pre>
1: { 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 }
</pre>
===Fast recursive===
A much better recursive approach, based on the formulas: <code>F(2k) = [2*F(k-1) + F(k)]*F(k)</code> and <code>F(2k+1) = F(k)² + F(k+1)²</code>
≪ '''IF''' DUP 2 ≤ '''THEN''' SIGN '''ELSE'''
'''IF''' DUP 2 MOD
'''THEN''' 1 - 2 / DUP <span style="color:blue">→FIB</span> SQ SWAP 1 + <span style="color:blue">→FIB</span> SQ +
'''ELSE''' 2 / DUP <span style="color:blue">→FIB</span> DUP ROT 1 - <span style="color:blue">→FIB</span> 2 * + *
'''END END'''
≫ '<span style="color:blue">→FIB</span>' STO


=={{header|Ruby}}==
=={{header|Ruby}}==
===Iterative===
===Iterative===
<lang ruby>def fib(n, sequence=[1])
<syntaxhighlight lang="ruby">def fib(n)
n.times do
if n < 2
n
current_number, last_number = sequence.last(2)
else
sequence << current_number + (last_number or 0)
prev, fib = 0, 1
(n-1).times do
prev, fib = fib, fib + prev
end
fib
end
end
end


p (0..10).map { |i| fib(i) }</syntaxhighlight>
sequence.last
Output:
end</lang>
<pre>
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
</pre>


===Recursive===
===Recursive===
<lang ruby>def fib(n, sequence=[1])
<syntaxhighlight lang="ruby">def fib(n, sequence=[1])
return sequence.last if n == 0
return sequence.last if n == 0


Line 8,489: Line 12,749:
fib(n-1, sequence)
fib(n-1, sequence)
end
end
</syntaxhighlight>
</lang>


===Recursive with Memoization===
===Recursive with Memoization===
<lang ruby># Use the Hash#default_proc feature to
<syntaxhighlight lang="ruby"># Use the Hash#default_proc feature to
# lazily calculate the Fibonacci numbers.
# lazily calculate the Fibonacci numbers.


Line 8,504: Line 12,764:
end
end
end
end
# examples: fib[10] => 55, fib[-10] => (-55/1)</lang>
# examples: fib[10] => 55, fib[-10] => (-55/1)</syntaxhighlight>


===Matrix===
===Matrix===
<lang ruby>require 'matrix'
<syntaxhighlight lang="ruby">require 'matrix'


# To understand why this matrix is useful for Fibonacci numbers, remember
# To understand why this matrix is useful for Fibonacci numbers, remember
Line 8,542: Line 12,802:
return nil if matrix.row_size == 0
return nil if matrix.row_size == 0
return matrix[matrix.row_size - 1, matrix.column_size - 1]
return matrix[matrix.row_size - 1, matrix.column_size - 1]
end</lang>
end</syntaxhighlight>


===Generative===
===Generative===
<lang ruby>fib = Enumerator.new do |y|
<syntaxhighlight lang="ruby">fib = Enumerator.new do |y|
f0, f1 = 0, 1
f0, f1 = 0, 1
loop do
loop do
Line 8,551: Line 12,811:
f0, f1 = f1, f0 + f1
f0, f1 = f1, f0 + f1
end
end
end</lang>
end</syntaxhighlight>


Usage:
Usage:
Line 8,560: Line 12,820:
"Fibers are primitives for implementing light weight cooperative concurrency in Ruby. Basically they are a means of creating code blocks that can be paused and resumed, much like threads. The main difference is that they are never preempted and that the scheduling must be done by the programmer and not the VM." [http://www.ruby-doc.org/ruby-1.9/classes/Fiber.html]
"Fibers are primitives for implementing light weight cooperative concurrency in Ruby. Basically they are a means of creating code blocks that can be paused and resumed, much like threads. The main difference is that they are never preempted and that the scheduling must be done by the programmer and not the VM." [http://www.ruby-doc.org/ruby-1.9/classes/Fiber.html]


<lang ruby>fib = Fiber.new do
<syntaxhighlight lang="ruby">fib = Fiber.new do
a,b = 0,1
a,b = 0,1
loop do
loop do
Line 8,567: Line 12,827:
end
end
end
end
9.times {puts fib.resume}</lang>
9.times {puts fib.resume}</syntaxhighlight>


using a lambda
using a lambda
<lang ruby>def fib_gen
<syntaxhighlight lang="ruby">def fib_gen
a, b = 1, 1
a, b = 1, 1
lambda {ret, a, b = a, b, a+b; ret}
lambda {ret, a, b = a, b, a+b; ret}
end</lang>
end</syntaxhighlight>


<pre>
<pre>
Line 8,592: Line 12,852:


===Binet's Formula===
===Binet's Formula===
<lang ruby>def fib
<syntaxhighlight lang="ruby">def fib
phi = (1 + Math.sqrt(5)) / 2
phi = (1 + Math.sqrt(5)) / 2
((phi**self - (-1 / phi)**self) / Math.sqrt(5)).to_i
((phi**self - (-1 / phi)**self) / Math.sqrt(5)).to_i
end</lang>
end</syntaxhighlight>
<pre>
<pre>
1.9.3p125 :001 > def fib
1.9.3p125 :001 > def fib
Line 8,605: Line 12,865:
=> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
=> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
</pre>
</pre>

=={{header|Run BASIC}}==
<lang runbasic>for i = 0 to 10
print i;" ";fibR(i);" ";fibI(i)
next i
end
function fibR(n)
if n < 2 then fibR = n else fibR = fibR(n-1) + fibR(n-2)
end function
function fibI(n)
b = 1
for i = 1 to n
t = a + b
a = b
b = t
next i
fibI = a
end function</lang>


=={{header|Rust}}==
=={{header|Rust}}==
===Iterative===
===Iterative===
<syntaxhighlight lang="rust">fn main() {
<lang rust>use std::mem;
fn main() {
let mut prev = 0;
let mut prev = 0;
// Rust needs this type hint for the checked_add method
// Rust needs this type hint for the checked_add method
Line 8,639: Line 12,878:
println!("{}", n);
println!("{}", n);
}
}
}</lang>
}</syntaxhighlight>


===Recursive===
===Recursive===
<lang rust>use std::mem;
<syntaxhighlight lang="rust">use std::mem;
fn main() {
fn main() {
fibonacci(0,1);
fibonacci(0,1);
Line 8,653: Line 12,892:
fibonacci(prev, n);
fibonacci(prev, n);
}
}
}</lang>
}</syntaxhighlight>

===Recursive (with pattern matching)===
<syntaxhighlight lang="rust">fn fib(n: u32) -> u32 {
match n {
0 => 0,
1 => 1,
n => fib(n - 1) + fib(n - 2),
}
}</syntaxhighlight>

===Tail recursive (with pattern matching)===
<syntaxhighlight lang="rust">fn fib_tail_recursive(nth: usize) -> usize {
fn fib_tail_iter(n: usize, prev_fib: usize, fib: usize) -> usize {
match n {
0 => prev_fib,
n => fib_tail_iter(n - 1, fib, prev_fib + fib),
}
}
fib_tail_iter(nth, 0, 1)
}</syntaxhighlight>


===Analytic===
===Analytic===
<syntaxhighlight lang="rust">fn main() {
This uses a feature from nightly Rust which makes it possible to (cleanly) return an iterator without the additional overhead of putting it on the heap. In stable Rust, we'd need to return a <code>Box<Iterator<Item=u64>></code> which has the cost of an additional allocation and the overhead of dynamic dispatch. The version below does not require the use of the heap and is done entirely through static dispatch.
for num in fibonacci_sequence() {
<lang rust>#![feature(conservative_impl_trait)]

fn main() {
for num in fibonacci_gen(10) {
println!("{}", num);
println!("{}", num);
}
}
}
}


fn fibonacci_gen(terms: i32) -> impl Iterator<Item=u64> {
fn fibonacci_sequence() -> impl Iterator<Item = u64> {
let sqrt_5 = 5.0f64.sqrt();
let sqrt_5 = 5.0f64.sqrt();
let p = (1.0 + sqrt_5) / 2.0;
let p = (1.0 + sqrt_5) / 2.0;
let q = 1.0/p;
let q = 1.0 / p;
// The range is sufficient up to 70th Fibonacci number
(1..terms).map(move |n| ((p.powi(n) + q.powi(n)) / sqrt_5 + 0.5) as u64)
(0..1).chain((1..70).map(move |n| ((p.powi(n) + q.powi(n)) / sqrt_5 + 0.5) as u64))
}</lang>
}</syntaxhighlight>


===Using an Iterator===
===Using an Iterator===
Iterators are very idiomatic in rust, though they may be overkill for such a simple problem.
Iterators are very idiomatic in rust, though they may be overkill for such a simple problem.
<lang rust>use std::mem;
<syntaxhighlight lang="rust">use std::mem;


struct Fib {
struct Fib {
Line 8,703: Line 12,959:
println!("{}", num);
println!("{}", num);
}
}
}</lang>
}</syntaxhighlight>


=={{header|SAS}}==


=== Iterative ===
====Iterator "Successors"====
<syntaxhighlight lang="rust">fn main() {
std::iter::successors(Some((1u128, 0)), |&(a, b)| a.checked_add(b).map(|s| (b, s)))
.for_each(|(_, u)| println!("{}", u));
}</syntaxhighlight>


This code builds a table <code>fib</code> holding the first few values of the Fibonacci sequence.


=={{header|SAS}}==
<lang sas>data fib;
=== Iterative ===
This code builds a table <code>fib</code> holding the first few values of the Fibonacci sequence.
<syntaxhighlight lang="sas">data fib;
a=0;
a=0;
b=1;
b=1;
Line 8,721: Line 12,982:
end;
end;
keep n f;
keep n f;
run;</lang>
run;</syntaxhighlight>


=== Naive recursive ===
=== Naive recursive ===

This code provides a simple example of defining a function and using it recursively. One of the members of the sequence is written to the log.
This code provides a simple example of defining a function and using it recursively. One of the members of the sequence is written to the log.


<lang sas>options cmplib=work.f;
<syntaxhighlight lang="sas">options cmplib=work.f;


proc fcmp outlib=work.f.p;
proc fcmp outlib=work.f.p;
Line 8,740: Line 13,000:
x = fib(5);
x = fib(5);
put 'fib(5) = ' x;
put 'fib(5) = ' x;
run;</lang>
run;</syntaxhighlight>


=={{header|Sather}}==
=={{header|Sather}}==
The implementations use the arbitrary precision class INTI.
The implementations use the arbitrary precision class INTI.
<lang sather>class MAIN is
<syntaxhighlight lang="sather">class MAIN is


-- RECURSIVE --
-- RECURSIVE --
Line 8,777: Line 13,037:
end;
end;


end;</lang>
end;</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
===Recursive===
===Recursive===
<lang scala>def fib(i:Int):Int = i match{
<syntaxhighlight lang="scala">def fib(i: Int): Int = i match {
case 0 => 0
case 0 => 0
case 1 => 1
case 1 => 1
case _ => fib(i-1) + fib(i-2)
case _ => fib(i - 1) + fib(i - 2)
}</lang>
}</syntaxhighlight>


===Lazy sequence===
===Lazy sequence===
<lang scala>lazy val fib: Stream[Int] = 0 #:: 1 #:: fib.zip(fib.tail).map{case (a,b) => a + b}</lang>
<syntaxhighlight lang="scala">lazy val fib: LazyList[Int] = 0 #:: 1 #:: fib.zip(fib.tail).map { case (a, b) => a + b }</syntaxhighlight>


===Tail recursive===
===Tail recursive===
<syntaxhighlight lang="scala">import scala.annotation.tailrec
<lang scala>def fib(x:Int, prev: BigInt = 0, next: BigInt = 1):BigInt = x match {
@tailrec
case 0 => prev
case _ => fib(x-1, next, next + prev)
final def fib(x: Int, prev: BigInt = 0, next: BigInt = 1): BigInt = x match {
case 0 => prev
}</lang>
case _ => fib(x - 1, next, next + prev)
}</syntaxhighlight>


===foldLeft===
===foldLeft===
<lang scala>// Fibonacci using BigInt with Stream.foldLeft optimized for GC (Scala v2.9 and above)
<syntaxhighlight lang="scala">// Fibonacci using BigInt with LazyList.foldLeft optimized for GC (Scala v2.13 and above)
// Does not run out of memory for very large Fibonacci numbers
// Does not run out of memory for very large Fibonacci numbers
def fib(n:Int) = {
def fib(n: Int): BigInt = {


def series(i:BigInt,j:BigInt):Stream[BigInt] = i #:: series(j, i+j)
def series(i: BigInt, j: BigInt): LazyList[BigInt] = i #:: series(j, i + j)


series(1,0).take(n).foldLeft(BigInt("0"))(_+_)
series(1, 0).take(n).foldLeft(BigInt("0"))(_ + _)
}
}


Line 8,810: Line 13,072:


// result: 0 1 1 2 3 5 8 13 21 34 55 89 144 233
// result: 0 1 1 2 3 5 8 13 21 34 55 89 144 233
</syntaxhighlight>
</lang>


===Iterator===
===Iterator===
<lang scala>val it = Iterator.iterate((0,1)){case (a,b) => (b,a+b)}.map(_._1)
<syntaxhighlight lang="scala">val it: Iterator[Int] = Iterator.iterate((0, 1)) { case (a, b) => (b, a + b) }.map(_._1)

//example:
def fib(n: Int): Int = it.drop(n).next()
println(it.take(13).mkString(",")) //prints: 0,1,1,2,3,5,8,13,21,34,55,89,144</lang>

// example:
println(it.take(13).mkString(",")) // prints: 0,1,1,2,3,5,8,13,21,34,55,89,144</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
===Iterative===
===Iterative===
<lang scheme>(define (fib-iter n)
<syntaxhighlight lang="scheme">(define (fib-iter n)
(do ((num 2 (+ num 1))
(do ((num 2 (+ num 1))
(fib-prev 1 fib)
(fib-prev 1 fib)
(fib 1 (+ fib fib-prev)))
(fib 1 (+ fib fib-prev)))
((>= num n) fib)))</lang>
((>= num n) fib)))</syntaxhighlight>


===Recursive===
===Recursive===
<lang scheme>(define (fib-rec n)
<syntaxhighlight lang="scheme">(define (fib-rec n)
(if (< n 2)
(if (< n 2)
n
n
(+ (fib-rec (- n 1))
(+ (fib-rec (- n 1))
(fib-rec (- n 2)))))</lang>
(fib-rec (- n 2)))))</syntaxhighlight>


This version is tail recursive:
This version is tail recursive:
<lang scheme>(define (fib n)
<syntaxhighlight lang="scheme">(define (fib n)
(let loop ((a 0) (b 1) (n n))
(let loop ((a 0) (b 1) (n n))
(if (= n 0) a
(if (= n 0) a
(loop b (+ a b) (- n 1)))))
(loop b (+ a b) (- n 1)))))
</syntaxhighlight>
</lang>


===Recursive Sequence Generator===
===Recursive Sequence Generator===
Line 8,845: Line 13,110:
The following procedure generates the sequence of Fibonacci numbers using a simplified version of a lazy list/stream - since no memoization is requried, it just implements future values by using a zero parameter lambda "thunk" with a closure containing the last and the pre-calculated next value of the sequence; in this way it uses almost no memory during the sequence generation other than as required for the last and the next values of the sequence (note that the test procedure does not generate a linked list to contain the elements of the sequence to show, but rather displays each one by one in sequence):
The following procedure generates the sequence of Fibonacci numbers using a simplified version of a lazy list/stream - since no memoization is requried, it just implements future values by using a zero parameter lambda "thunk" with a closure containing the last and the pre-calculated next value of the sequence; in this way it uses almost no memory during the sequence generation other than as required for the last and the next values of the sequence (note that the test procedure does not generate a linked list to contain the elements of the sequence to show, but rather displays each one by one in sequence):


<lang scheme>
<syntaxhighlight lang="scheme">
(define (fib)
(define (fib)
(define (nxt lv nv) (cons nv (lambda () (nxt nv (+ lv nv)))))
(define (nxt lv nv) (cons nv (lambda () (nxt nv (+ lv nv)))))
Line 8,855: Line 13,120:
(if (> n 1) (begin (display " ") (shw-nxt (- n 1) ((cdr strm)))) (display ")"))))
(if (> n 1) (begin (display " ") (shw-nxt (- n 1) ((cdr strm)))) (display ")"))))
(begin (display "(") (shw-nxt n strm)))
(begin (display "(") (shw-nxt n strm)))
(show-stream-take 30 (fib))</lang>
(show-stream-take 30 (fib))</syntaxhighlight>


{{output}}
{{output}}
Line 8,861: Line 13,126:


===Dijkstra Algorithm===
===Dijkstra Algorithm===
<lang scheme>;;; Fibonacci numbers using Edsger Dijkstra's algorithm
<syntaxhighlight lang="scheme">;;; Fibonacci numbers using Edsger Dijkstra's algorithm
;;; http://www.cs.utexas.edu/users/EWD/ewd06xx/EWD654.PDF
;;; http://www.cs.utexas.edu/users/EWD/ewd06xx/EWD654.PDF


Line 8,879: Line 13,144:
q
q
(- count 1)))))
(- count 1)))))
(fib-aux 1 0 0 1 n))</lang>
(fib-aux 1 0 0 1 n))</syntaxhighlight>


=={{header|Scilab}}==
=={{header|Scilab}}==
<lang> clear
<syntaxhighlight lang="text"> clear
n=46
n=46
f1=0; f2=1
f1=0; f2=1
Line 8,892: Line 13,157:
f1=f2
f1=f2
f2=f3
f2=f3
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>...
<pre>...
Line 8,901: Line 13,166:


=={{header|sed}}==
=={{header|sed}}==
<lang sed>#!/bin/sed -f
<syntaxhighlight lang="sed">#!/bin/sed -f


# First we need to convert each number into the right number of ticks
# First we need to convert each number into the right number of ticks
Line 8,940: Line 13,205:
s/</|/g
s/</|/g
t back
t back
s/^$/0/</lang>
s/^$/0/</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
===Recursive===
===Recursive===
<lang seed7>const func integer: fib (in integer: number) is func
<syntaxhighlight lang="seed7">const func integer: fib (in integer: number) is func
result
result
var integer: result is 1;
var integer: result is 1;
Line 8,953: Line 13,218:
result := 0;
result := 0;
end if;
end if;
end func;</lang>
end func;</syntaxhighlight>


Original source: [http://seed7.sourceforge.net/algorith/math.htm#fib]
Original source: [http://seed7.sourceforge.net/algorith/math.htm#fib]
Line 8,960: Line 13,225:
This funtion uses a bigInteger result:
This funtion uses a bigInteger result:


<lang seed7>const func bigInteger: fib (in integer: number) is func
<syntaxhighlight lang="seed7">const func bigInteger: fib (in integer: number) is func
result
result
var bigInteger: result is 1_;
var bigInteger: result is 1_;
Line 8,973: Line 13,238:
result +:= c;
result +:= c;
end for;
end for;
end func;</lang>
end func;</syntaxhighlight>


Original source: [http://seed7.sourceforge.net/algorith/math.htm#iterative_fib]
Original source: [http://seed7.sourceforge.net/algorith/math.htm#iterative_fib]
Line 8,979: Line 13,244:
=={{header|SequenceL}}==
=={{header|SequenceL}}==
===Recursive===
===Recursive===
<lang sequencel>fibonacci(n) :=
<syntaxhighlight lang="sequencel">fibonacci(n) :=
n when n < 2
n when n < 2
else
else
fibonacci(n - 1) + fibonacci(n - 2);</lang>
fibonacci(n - 1) + fibonacci(n - 2);</syntaxhighlight>
Based on: [https://www.youtube.com/watch?v=5JVC5dDtnyg]
Based on: [https://www.youtube.com/watch?v=5JVC5dDtnyg]


===Tail Recursive===
===Tail Recursive===
<lang sequencel>fibonacci(n) := fibonacciHelper(0, 1, n);
<syntaxhighlight lang="sequencel">fibonacci(n) := fibonacciHelper(0, 1, n);
fibonacciHelper(prev, next, n) :=
fibonacciHelper(prev, next, n) :=
Line 8,993: Line 13,258:
next when n = 1
next when n = 1
else
else
fibonacciHelper(next, next + prev, n - 1);</lang>
fibonacciHelper(next, next + prev, n - 1);</syntaxhighlight>


===Matrix===
===Matrix===
<lang sequencel>fibonacci(n) := fibonacciHelper([[1,0],[0,1]], n);
<syntaxhighlight lang="sequencel">fibonacci(n) := fibonacciHelper([[1,0],[0,1]], n);


fibonacciHelper(M(2), n) :=
fibonacciHelper(M(2), n) :=
Line 9,006: Line 13,271:
fibonacciHelper(matmul(M, N), n - 1);
fibonacciHelper(matmul(M, N), n - 1);


matmul(A(2), B(2)) [i,j] := sum( A[i,all] * B[all,j] );</lang>
matmul(A(2), B(2)) [i,j] := sum( A[i,all] * B[all,j] );</syntaxhighlight>
Based on the C# version: [http://rosettacode.org/wiki/Fibonacci_sequence#C.23]
Based on the C# version: [http://rosettacode.org/wiki/Fibonacci_sequence#C.23]


Line 9,012: Line 13,277:


=={{header|SETL}}==
=={{header|SETL}}==
<lang setl>$ Print out the first ten Fibonacci numbers
<syntaxhighlight lang="setl">$ Print out the first ten Fibonacci numbers
$ This uses Set Builder Notation, it roughly means
$ This uses Set Builder Notation, it roughly means
$ 'collect fib(n) forall n in {0,1,2,3,4,5,6,7,8,9,10}'
$ 'collect fib(n) forall n in {0,1,2,3,4,5,6,7,8,9,10}'
Line 9,026: Line 13,291:
end loop;
end loop;
return C;
return C;
end proc;</lang>
end proc;</syntaxhighlight>



=={{header|Shen}}==
=={{header|Shen}}==
<lang Shen>(define fib
<syntaxhighlight lang="shen">(define fib
0 -> 0
0 -> 0
1 -> 1
1 -> 1
N -> (+ (fib (+ N 1)) (fib (+ N 2)))
N -> (+ (fib (+ N 1)) (fib (+ N 2)))
where (< N 0)
where (< N 0)
N -> (+ (fib (- N 1)) (fib (- N 2))))</lang>
N -> (+ (fib (- N 1)) (fib (- N 2))))</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
===Iterative===
===Iterative===
<lang ruby>func fib_iter(n) {
<syntaxhighlight lang="ruby">func fib_iter(n) {
var (a, b) = (0, 1)
var (a, b) = (0, 1)
{ (a, b) = (b, a+b) } * n
{ (a, b) = (b, a+b) } * n
return a
return a
}</lang>
}</syntaxhighlight>


===Recursive===
===Recursive===
<lang ruby>func fib_rec(n) {
<syntaxhighlight lang="ruby">func fib_rec(n) {
n < 2 ? n : (__FUNC__(n-1) + __FUNC__(n-2))
n < 2 ? n : (__FUNC__(n-1) + __FUNC__(n-2))
}</lang>
}</syntaxhighlight>


===Recursive with memoization===
===Recursive with memoization===
<lang ruby>func fib_mem (n) is cached {
<syntaxhighlight lang="ruby">func fib_mem (n) is cached {
n < 2 ? n : (__FUNC__(n-1) + __FUNC__(n-2))
n < 2 ? n : (__FUNC__(n-1) + __FUNC__(n-2))
}</lang>
}</syntaxhighlight>


===Closed-form===
===Closed-form===
<lang ruby>func fib_closed(n) {
<syntaxhighlight lang="ruby">func fib_closed(n) {
define S = (1.25.sqrt + 0.5)
define S = (1.25.sqrt + 0.5)
define T = (-S + 1)
define T = (-S + 1)
(S**n - T**n) / (-T + S) -> round
(S**n - T**n) / (-T + S) -> round
}</lang>
}</syntaxhighlight>


===Built-in===
===Built-in===
<lang ruby>say fib(12) #=> 144</lang>
<syntaxhighlight lang="ruby">say fib(12) #=> 144</syntaxhighlight>


=={{header|Simula}}==
=={{header|Simula}}==
Straightforward iterative implementation.
Straightforward iterative implementation.
<lang simula>INTEGER PROCEDURE fibonacci(n);
<syntaxhighlight lang="simula">INTEGER PROCEDURE fibonacci(n);
INTEGER n;
INTEGER n;
BEGIN
BEGIN
Line 9,080: Line 13,344:
END;
END;
fibonacci := hi
fibonacci := hi
END;</lang>
END;</syntaxhighlight>


=={{header|SkookumScript}}==
=={{header|SkookumScript}}==
Line 9,088: Line 13,352:
SkookumScript's <code>Integer</code> class has a fast built-in <code>fibonnaci()</code> method.
SkookumScript's <code>Integer</code> class has a fast built-in <code>fibonnaci()</code> method.


<lang javascript>42.fibonacci</lang>
<syntaxhighlight lang="javascript">42.fibonacci</syntaxhighlight>


SkookumScript is designed to work in tandem with C++ and its strength is at the high-level stage-direction of things. So when confronted with [http://skookumscript.com/blog/2016/07-11-fibonacci/ benchmarking scripting systems] it is genrally better to make a built-in call. Though in most practical cases this isn't necessary.
SkookumScript is designed to work in tandem with C++ and its strength is at the high-level stage-direction of things. So when confronted with [http://skookumscript.com/blog/2016/07-11-fibonacci/ benchmarking scripting systems] it is genrally better to make a built-in call. Though in most practical cases this isn't necessary.
Line 9,096: Line 13,360:
Simple recursive method in same <code>42.fibonacci</code> form as built-in form above.
Simple recursive method in same <code>42.fibonacci</code> form as built-in form above.


<lang javascript>// Assuming code is in Integer.fibonacci() method
<syntaxhighlight lang="javascript">// Assuming code is in Integer.fibonacci() method
() Integer
() Integer
[
[
if this < 2 [this] else [[this - 1].fibonacci + [this - 2].fibonacci]
if this < 2 [this] else [[this - 1].fibonacci + [this - 2].fibonacci]
]</lang>
]</syntaxhighlight>


Recursive procedure in <code>fibonacci(42)</code> form.
Recursive procedure in <code>fibonacci(42)</code> form.


<lang javascript>// Assuming in fibonacci(n) procedure
<syntaxhighlight lang="javascript">// Assuming in fibonacci(n) procedure
(Integer n) Integer
(Integer n) Integer
[
[
if n < 2 [n] else [fibonacci(n - 1) + fibonacci(n - 2)]
if n < 2 [n] else [fibonacci(n - 1) + fibonacci(n - 2)]
]</lang>
]</syntaxhighlight>


===Iterative===
===Iterative===
Line 9,114: Line 13,378:
Iterative method in <code>42.fibonacci</code> form.
Iterative method in <code>42.fibonacci</code> form.


<lang javascript>// Assuming code is in Integer.fibonacci() method
<syntaxhighlight lang="javascript">// Assuming code is in Integer.fibonacci() method
() Integer
() Integer
[
[
Line 9,132: Line 13,396:
next
next
]
]
]</lang>
]</syntaxhighlight>
Optimized iterative method in <code>42.fibonacci</code> form.
Optimized iterative method in <code>42.fibonacci</code> form.
Though the best optimiation is to write it in C++ as with the built-in form that comes with SkookumScript.
Though the best optimiation is to write it in C++ as with the built-in form that comes with SkookumScript.


<lang javascript>// Bind : is faster than assignment :=
<syntaxhighlight lang="javascript">// Bind : is faster than assignment :=
// loop is faster than to_pre (which uses a closure)
// loop is faster than to_pre (which uses a closure)
() Integer
() Integer
Line 9,160: Line 13,424:
next
next
]
]
]</lang>
]</syntaxhighlight>



=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>n@(Integer traits) fib
<syntaxhighlight lang="slate">n@(Integer traits) fib
[
[
n <= 0 ifTrue: [^ 0].
n <= 0 ifTrue: [^ 0].
Line 9,172: Line 13,435:


slate[15]> 10 fib = 55.
slate[15]> 10 fib = 55.
True</lang>
True</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
Smalltalk already has a builtin fib in the Integer class (so I call them fibI and fibR in the code below, to not overwrite it).
<lang smalltalk>|fibo|
The integer algorithms below are all naive; there are faster ways to do it (see benchmark at the end).
fibo := [ :i |
I gave the recursive version roughly 100Mb of stack.
|ac t|
The analytical computation generates inexact results and fails for arguments somewhere above 1470 due to floating point overflow
ac := Array new: 2.
(with extended precision, the overflow appears a bit later).
ac at: 1 put: 0 ; at: 2 put: 1.
( i < 2 )
ifTrue: [ ac at: (i+1) ]
ifFalse: [
2 to: i do: [ :l |
t := (ac at: 2).
ac at: 2 put: ( (ac at: 1) + (ac at: 2) ).
ac at: 1 put: t
].
ac at: 2.
]
].


iterative (slow):
0 to: 10 do: [ :i |
<syntaxhighlight lang="smalltalk">Integer >> fibI
(fibo value: i) displayNl
|aNMinus1 an t|
]</lang>


aNMinus1 := 1.
an := 0.
self timesRepeat:[
t := an.
an := an + aNMinus1 .
aNMinus1 := t.
].
^ an</syntaxhighlight>
The recursive version although nice to read is the worst; it suffers from a huge stack requirement and a super poor performance (an anti-example for recursion):
<syntaxhighlight lang="smalltalk">Integer >> fibR
(self > 1) ifTrue:[
^ (self - 1) fibR + (self - 2) fibR
].
^ self</syntaxhighlight>
analytic (fast, but inexact, and limited to small n below 1475 if we use double precision IEEE floats):
<syntaxhighlight lang="smalltalk">Integer >> fibBinet
|phi rPhi|


phi := Float phi.
=={{header|smart BASIC}}==
rPhi := 1 / phi.


^ (1 / 5 sqrt) * ((phi raisedTo:self) - (rPhi raisedTo:self))</syntaxhighlight>
The Iterative method is slow (relatively) and the Recursive method doubly so since it references the Iterative function twice.
using more bits in the exponent, we can compute larger fibs (up to 23599 with x86 extended precision floats), but still inexact:
<syntaxhighlight lang="smalltalk">Integer >> fibBinetFloatE
|phi rPhi|


phi := FloatE phi.
The N-th Term (fibN) function is much faster as it utilizes Binet's Formula.
rPhi := 1 / phi.


^ (1 / 5 sqrt) * ((phi raisedTo:self) - (rPhi raisedTo:self))</syntaxhighlight>
<ul>
<syntaxhighlight lang="smalltalk">
<li>fibR: Fibonacci Recursive</li>
(10 to:1e6 byFactor:10) do:[:n |
<li>fibI: Fibonacci Iterative</li>
Transcript printCR:'----',n,'----'.
<li>fibN: Fibonacci N-th Term</li>
Transcript printCR: n fibI.
</ul>
Transcript printCR: ([[n fibR] on:RecursionError do:['recursion']] valueWithTimeout:30 seconds) ? 'timeout'.
Transcript printCR: n fibBinet.
Transcript printCR: n fibBinetFloatE.
].


Transcript cr; showCR:'Timing:'; showCR:'------'.
<lang qbasic>FOR i = 0 TO 15
[ 1000 fibI ] benchmark:'1000 fibI'.
PRINT fibR(i),fibI(i),fibN(i)
[ 1000 fibR ] benchmark:'1000 fibR' timeLimit:30 seconds.
NEXT i
[ 1000 fibBinet ] benchmark:'1000 fibBinet'.
[ 1000 fibBinetFloatE] benchmark:'1000 fibBinetFloatE'.
[ 1000 fib ] benchmark:'1000 fib (builtin)'.


[ 10000 fibI ] benchmark:'10000 fibI'.
/* Recursive Method */
[ 10000 fib ] benchmark:'10000 fib (builtin)'.
DEF fibR(n)
IF n <= 1 THEN
fibR = n
ELSE
fibR = fibR(n-1) + fibR(n-2)
ENDIF
END DEF


[ 100000 fibI ] benchmark:'100000 fibI'.
/* Iterative Method */
[ 100000 fib ] benchmark:'100000 fib (builtin)'.
DEF fibI(n)
a = 0
b = 1
FOR i = 1 TO n
temp = a + b
a = b
b = temp
NEXT i
fibI = a
END DEF


[ 1000000 fibI ] benchmark:'100000 fibI'.
/* N-th Term Method */
[ 1000000 fib ] benchmark:'1000000 fib (builtin)'.
DEF fibN(n)
[ 2000000 fib ] benchmark:'2000000 fib (builtin)'.
uphi = .5 + SQR(5)/2
[ 10000000 fib ] benchmark:'10000000 fib (builtin)'</syntaxhighlight>
lphi = .5 - SQR(5)/2
{{out}}
fibN = (uphi^n-lphi^n)/SQR(5)
<pre>----10----
END DEF</lang>
55
55
55.0
54.99999999999
----100----
354224848179261915075
timeout
3.54224848179262E+020
3.54224848179263E+020
----1000----
43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875
timeout
4.34665576869373E+208
4.34665576869373E+208
----10000----
336447648764317832666216120051075433103021...050562430701794976171121233066073310059947366875 (2089 digits)
timeout
INF
3.364476487643176087E+2089
----100000----
259740693472217241661550340212759154148804853...653428746875 (20898 digits)
recursion
INF
INF
----1000000----
19532821287077577316320149475962563324435429965918733...2043347225419033684684301719893411568996526838242546875 (208987 digits)
recursion
INF
INF

Timing:
-------
1000 fibI: 94 µs (394736 cycles)
timeout after 30000ms
1000 fibBinet: 5500 ns (21746 cycles)
1000 fibBinetFloatE: 12 µs (43444 cycles)
1000 fib (builtin): 37 µs (130842 cycles)
10000 fibI: 2.44 ms (8775334 cycles)
10000 fib (builtin): 49 µs (175466 cycles)
100000 fibI: 156ms (563848550 cycles)
100000 fib (builtin): 1.66 ms (5970368 cycles)
1000000 fibI: 14.3s (51676292910 cycles)
1000000 fib (builtin): 71.95 ms (259023588 cycles)
2000000 fib (builtin): 229ms (827461038 cycles)
10000000 fib (builtin): 2.769s (9970686190 cycles)</pre>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==

===Recursive===
===Recursive===
<lang snobol> define("fib(a)") :(fib_end)
<syntaxhighlight lang="snobol"> define("fib(a)") :(fib_end)
fib fib = lt(a,2) a :s(return)
fib fib = lt(a,2) a :s(return)
fib = fib(a - 1) + fib(a - 2) :(return)
fib = fib(a - 1) + fib(a - 2) :(return)
Line 9,251: Line 13,562:
while a = trim(input) :f(end)
while a = trim(input) :f(end)
output = a " " fib(a) :(while)
output = a " " fib(a) :(while)
end</lang>
end</syntaxhighlight>


===Tail-recursive===
===Tail-recursive===
<lang SNOBOL4> define('trfib(n,a,b)') :(trfib_end)
<syntaxhighlight lang="snobol4"> define('trfib(n,a,b)') :(trfib_end)
trfib trfib = eq(n,0) a :s(return)
trfib trfib = eq(n,0) a :s(return)
trfib = trfib(n - 1, a + b, a) :(return)
trfib = trfib(n - 1, a + b, a) :(return)
trfib_end</lang>
trfib_end</syntaxhighlight>


===Iterative===
===Iterative===
<lang SNOBOL4> define('ifib(n)f1,f2') :(ifib_end)
<syntaxhighlight lang="snobol4"> define('ifib(n)f1,f2') :(ifib_end)
ifib ifib = le(n,2) 1 :s(return)
ifib ifib = le(n,2) 1 :s(return)
f1 = 1; f2 = 1
f1 = 1; f2 = 1
if1 ifib = gt(n,2) f1 + f2 :f(return)
if1 ifib = gt(n,2) f1 + f2 :f(return)
f1 = f2; f2 = ifib; n = n - 1 :(if1)
f1 = f2; f2 = ifib; n = n - 1 :(if1)
ifib_end</lang>
ifib_end</syntaxhighlight>


===Analytic===
===Analytic===
Line 9,272: Line 13,583:
Note: Snobol4+ lacks built-in sqrt( ) function.
Note: Snobol4+ lacks built-in sqrt( ) function.


<lang SNOBOL4> define('afib(n)s5') :(afib_end)
<syntaxhighlight lang="snobol4"> define('afib(n)s5') :(afib_end)
afib s5 = sqrt(5)
afib s5 = sqrt(5)
afib = (((1 + s5) / 2) ^ n - ((1 - s5) / 2) ^ n) / s5
afib = (((1 + s5) / 2) ^ n - ((1 - s5) / 2) ^ n) / s5
afib = convert(afib,'integer') :(return)
afib = convert(afib,'integer') :(return)
afib_end</lang>
afib_end</syntaxhighlight>


Test and display all, Fib 1 .. 10
Test and display all, Fib 1 .. 10


<lang SNOBOL4>loop i = lt(i,10) i + 1 :f(show)
<syntaxhighlight lang="snobol4">loop i = lt(i,10) i + 1 :f(show)
s1 = s1 fib(i) ' ' ; s2 = s2 trfib(i,0,1) ' '
s1 = s1 fib(i) ' ' ; s2 = s2 trfib(i,0,1) ' '
s3 = s3 ifib(i) ' '; s4 = s4 afib(i) ' ' :(loop)
s3 = s3 ifib(i) ' '; s4 = s4 afib(i) ' ' :(loop)
show output = s1; output = s2; output = s3; output = s4
show output = s1; output = s2; output = s3; output = s4
end</lang>
end</syntaxhighlight>


Output:
Output:
Line 9,296: Line 13,607:


===Iterative===
===Iterative===
<lang snusp> @!\+++++++++# /<<+>+>-\
<syntaxhighlight lang="snusp"> @!\+++++++++# /<<+>+>-\
fib\==>>+<<?!/>!\ ?/\
fib\==>>+<<?!/>!\ ?/\
#<</?\!>/@>\?-<<</@>/@>/>+<-\
#<</?\!>/@>\?-<<</@>/@>/>+<-\
\-/ \ !\ !\ !\ ?/#</lang>
\-/ \ !\ !\ !\ ?/#</syntaxhighlight>


===Recursive===
===Recursive===
<lang snusp> /========\ />>+<<-\ />+<-\
<syntaxhighlight lang="snusp"> /========\ />>+<<-\ />+<-\
fib==!/?!\-?!\->+>+<<?/>>-@\=====?/<@\===?/<#
fib==!/?!\-?!\->+>+<<?/>>-@\=====?/<@\===?/<#
| #+==/ fib(n-2)|+fib(n-1)|
| #+==/ fib(n-2)|+fib(n-1)|
\=====recursion======/!========/</lang>
\=====recursion======/!========/</syntaxhighlight>


=={{header|Softbridge BASIC}}==
=={{header|Spin}}==
===Iterative===
=== Iterative ===
{{works with|BST/BSTC}}
<lang basic>
{{works with|FastSpin/FlexSpin}}
Function Fibonacci(n)
{{works with|HomeSpun}}
x = 0
{{works with|OpenSpin}}
y = 1
<syntaxhighlight lang="spin">con
i = 0
_clkmode = xtal1 + pll16x
n = ABS(n)
_clkfreq = 80_000_000
If n < 2 Then
Fibonacci = n
obj
Else
ser : "FullDuplexSerial.spin"
Do Until (i = n)
sum = x+y
pub main | i
x=y
ser.start(31, 30, 0, 115200)
y=sum
i=i+1
Loop
Fibonacci = x
End If


repeat i from 0 to 10
End Function
ser.dec(fib(i))
</lang>
ser.tx(32)

waitcnt(_clkfreq + cnt)
ser.stop
cogstop(0)

pub fib(i) : b | a
b := a := 1
repeat i
a := b + (b := a)</syntaxhighlight>
{{out}}
<pre>1 1 2 3 5 8 13 21 34 55 89</pre>


=={{header|SPL}}==
=={{header|SPL}}==
=== Analytic ===
=== Analytic ===
<lang spl>fibo(n)=
<syntaxhighlight lang="spl">fibo(n)=
s5 = #.sqrt(5)
s5 = #.sqrt(5)
<= (((1+s5)/2)^n-((1-s5)/2)^n)/s5
<= (((1+s5)/2)^n-((1-s5)/2)^n)/s5
.</lang>
.</syntaxhighlight>
=== Iterative ===
=== Iterative ===
<lang spl>fibo(n)=
<syntaxhighlight lang="spl">fibo(n)=
? n<2, <= n
? n<2, <= n
f2 = 0
f2 = 0
Line 9,347: Line 13,666:
<
<
<= f
<= f
.</lang>
.</syntaxhighlight>
=== Recursive ===
=== Recursive ===
<lang spl>fibo(n)=
<syntaxhighlight lang="spl">fibo(n)=
? n<2, <= n
? n<2, <= n
<= fibo(n-1)+fibo(n-2)
<= fibo(n-1)+fibo(n-2)
.</lang>
.</syntaxhighlight>


=={{header|SQL}}==
=={{header|SQL}}==
=== Analytic ===
=== Analytic ===
As a running sum:
As a running sum:
<syntaxhighlight lang="sql">
<lang SQL>
select round ( exp ( sum (ln ( ( 1 + sqrt( 5 ) ) / 2)
select round ( exp ( sum (ln ( ( 1 + sqrt( 5 ) ) / 2)
) over ( order by level ) ) / sqrt( 5 ) ) fibo
) over ( order by level ) ) / sqrt( 5 ) ) fibo
from dual
from dual
connect by level <= 10;
connect by level <= 10;
</syntaxhighlight>
</lang>
<pre>
<pre>
FIB
FIB
Line 9,380: Line 13,699:
</pre>
</pre>
As a power:
As a power:
<syntaxhighlight lang="sql">
<lang SQL>
select round ( power( ( 1 + sqrt( 5 ) ) / 2, level ) / sqrt( 5 ) ) fib
select round ( power( ( 1 + sqrt( 5 ) ) / 2, level ) / sqrt( 5 ) ) fib
from dual
from dual
connect by level <= 10;
connect by level <= 10;
</syntaxhighlight>
</lang>
<pre>
<pre>
FIB
FIB
Line 9,406: Line 13,725:


Oracle 12c required
Oracle 12c required
<lang sql>
<syntaxhighlight lang="sql">
SQL> with fib(e,f) as (select 1, 1 from dual union all select e+f,e from fib where e <= 55) select f from fib;
SQL> with fib(e,f) as (select 1, 1 from dual union all select e+f,e from fib where e <= 55) select f from fib;


Line 9,423: Line 13,742:


10 rows selected.
10 rows selected.
</syntaxhighlight>
</lang>


{{works with|PostgreSQL}}
{{works with|PostgreSQL}}


<lang postgresql>CREATE FUNCTION fib(n int) RETURNS numeric AS $$
<syntaxhighlight lang="postgresql">CREATE FUNCTION fib(n int) RETURNS numeric AS $$
-- This recursive with generates endless list of Fibonacci numbers.
-- This recursive with generates endless list of Fibonacci numbers.
WITH RECURSIVE fibonacci(current, previous) AS (
WITH RECURSIVE fibonacci(current, previous) AS (
Line 9,453: Line 13,772:
-- position in the list.
-- position in the list.
OFFSET n
OFFSET n
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT IMMUTABLE;</lang>
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT IMMUTABLE;</syntaxhighlight>


=={{header|SSEM}}==
=={{header|SSEM}}==
Calculates the tenth Fibonacci number. To calculate the <i>n</i>th, change the initial value of the counter to <i>n</i>-1 (subject to the restriction that the answer must be small enough to fit in a signed 32-bit integer, the SSEM's only data type). The algorithm is basically straightforward, but the absence of an Add instruction makes the implementation a little more complicated than it would otherwise be.
Calculates the tenth Fibonacci number. To calculate the <i>n</i>th, change the initial value of the counter to <i>n</i>-1 (subject to the restriction that the answer must be small enough to fit in a signed 32-bit integer, the SSEM's only data type). The algorithm is basically straightforward, but the absence of an Add instruction makes the implementation a little more complicated than it would otherwise be.
<lang ssem>10101000000000100000000000000000 0. -21 to c acc = -n
<syntaxhighlight lang="ssem">10101000000000100000000000000000 0. -21 to c acc = -n
01101000000001100000000000000000 1. c to 22 temp = acc
01101000000001100000000000000000 1. c to 22 temp = acc
00101000000001010000000000000000 2. Sub. 20 acc -= m
00101000000001010000000000000000 2. Sub. 20 acc -= m
Line 9,482: Line 13,801:
10010000000000000000000000000000 23. 9 var count = 9
10010000000000000000000000000000 23. 9 var count = 9
11111111111111111111111111111111 24. -1 const -1
11111111111111111111111111111111 24. -1 const -1
11110000000000000000000000000000 25. 15 const 15</lang>
11110000000000000000000000000000 25. 15 const 15</syntaxhighlight>


=={{header|Stata}}==
=={{header|Stata}}==


<lang stata>program fib
<syntaxhighlight lang="stata">program fib
args n
args n
clear
clear
Line 9,492: Line 13,811:
qui gen a=1
qui gen a=1
qui replace a=a[_n-1]+a[_n-2] in 3/l
qui replace a=a[_n-1]+a[_n-2] in 3/l
end</lang>
end</syntaxhighlight>


An implementation using '''[https://www.stata.com/help.cgi?dyngen dyngen]'''.
An implementation using '''[https://www.stata.com/help.cgi?dyngen dyngen]'''.


<lang stata>program fib
<syntaxhighlight lang="stata">program fib
args n
args n
clear
clear
Line 9,507: Line 13,826:


fib 10
fib 10
list</lang>
list</syntaxhighlight>


'''Output'''
'''Output'''
Line 9,528: Line 13,847:


=== Mata ===
=== Mata ===
<lang stata>. mata
<syntaxhighlight lang="stata">. mata
: function fib(n) {
: function fib(n) {
return((((1+sqrt(5))/2):^n-((1-sqrt(5))/2):^n)/sqrt(5))
return((((1+sqrt(5))/2):^n-((1-sqrt(5))/2):^n)/sqrt(5))
Line 9,539: Line 13,858:
+--------------------------------------------------------+
+--------------------------------------------------------+


: end</lang>
: end</syntaxhighlight>


=={{header|StreamIt}}==
=={{header|StreamIt}}==
<lang streamit>void->int feedbackloop Fib {
<syntaxhighlight lang="streamit">void->int feedbackloop Fib {
join roundrobin(0,1);
join roundrobin(0,1);
body in->int filter {
body in->int filter {
Line 9,551: Line 13,870:
enqueue(0);
enqueue(0);
enqueue(1);
enqueue(1);
}</lang>
}</syntaxhighlight>


=={{header|SuperCollider}}==
=={{header|SuperCollider}}==
===Recursive===
===Recursive===
nth fibonacci term for positive n
nth fibonacci term for positive n
<syntaxhighlight lang="supercollider">
<lang SuperCollider>
f = { |n| if(n < 2) { n } { f.(n-1) + f.(n-2) } };
f = { |n| if(n < 2) { n } { f.(n-1) + f.(n-2) } };
(0..20).collect(f)
(0..20).collect(f)
</syntaxhighlight>
</lang>


nth fibonacci term for positive and negative n.
nth fibonacci term for positive and negative n.
<syntaxhighlight lang="supercollider">
<lang SuperCollider>
f = { |n| var u = neg(sign(n)); if(abs(n) < 2) { n } { f.(2 * u + n) + f.(u + n) } };
f = { |n| var u = neg(sign(n)); if(abs(n) < 2) { n } { f.(2 * u + n) + f.(u + n) } };
(-20..20).collect(f)
(-20..20).collect(f)
</syntaxhighlight>
</lang>


===Analytic===
===Analytic===
<syntaxhighlight lang="supercollider">(
<lang SuperCollider>(
f = { |n|
f = { |n|
var sqrt5 = sqrt(5);
var sqrt5 = sqrt(5);
Line 9,576: Line 13,895:
};
};
(0..20).collect(f)
(0..20).collect(f)
)</lang>
)</syntaxhighlight>


===Iterative===
===Iterative===
<syntaxhighlight lang="supercollider">
<lang SuperCollider>
f = { |n| var a = [1, 1]; n.do { a = a.addFirst(a[0] + a[1]) }; a.reverse };
f = { |n| var a = [1, 1]; n.do { a = a.addFirst(a[0] + a[1]) }; a.reverse };
f.(18)
f.(18)
</syntaxhighlight>
</lang>


=={{header|Swift}}==
=={{header|Swift}}==
===Analytic===
===Analytic===
<lang Swift>import Cocoa
<syntaxhighlight lang="swift">import Cocoa


func fibonacci(n: Int) -> Int {
func fibonacci(n: Int) -> Int {
Line 9,597: Line 13,916:
for i in 1...30 {
for i in 1...30 {
println(fibonacci(i))
println(fibonacci(i))
}</lang>
}</syntaxhighlight>


===Iterative===
===Iterative===
<lang Swift>func fibonacci(n: Int) -> Int {
<syntaxhighlight lang="swift">func fibonacci(n: Int) -> Int {
if n < 2 {
if n < 2 {
return n
return n
Line 9,610: Line 13,929:
}
}
return fib
return fib
}</lang>
}</syntaxhighlight>
Sequence:
Sequence:
<lang swift>func fibonacci() -> SequenceOf<UInt> {
<syntaxhighlight lang="swift">func fibonacci() -> SequenceOf<UInt> {
return SequenceOf {() -> GeneratorOf<UInt> in
return SequenceOf {() -> GeneratorOf<UInt> in
var window: (UInt, UInt, UInt) = (0, 0, 1)
var window: (UInt, UInt, UInt) = (0, 0, 1)
Line 9,620: Line 13,939:
}
}
}
}
}</lang>
}</syntaxhighlight>


===Recursive===
===Recursive===
<lang Swift>func fibonacci(n: Int) -> Int {
<syntaxhighlight lang="swift">func fibonacci(n: Int) -> Int {
if n < 2 {
if n < 2 {
return n
return n
Line 9,631: Line 13,950:
}
}


println(fibonacci(30))</lang>
println(fibonacci(30))</syntaxhighlight>

=={{header|Tailspin}}==
===Recursive simple===
The simplest exponential-time recursive algorithm only handling positive N. Note that the "#" is the tailspin internal recursion which sends the value to the matchers. In this case where there is no initial block and no templates state, we could equivalently write the templates name "nthFibonacci" in place of the "#" to do a normal recursion.
<syntaxhighlight lang="tailspin">
templates nthFibonacci
when <=0|=1> do $ !
otherwise ($ - 1 -> #) + ($ - 2 -> #) !
end nthFibonacci
</syntaxhighlight>

===Iterative, mutable state===
We could use the templates internal mutable state, still only positive N.
<syntaxhighlight lang="tailspin">
templates nthFibonacci
@: {n0: 0"1", n1: 1"1"};
1..$ -> @: {n0: $@.n1, n1: $@.n0 + $@.n1};
$@.n0!
end nthFibonacci
</syntaxhighlight>
To handle negatives, we can keep track of the sign and send it to the matchers.
<syntaxhighlight lang="tailspin">
templates nthFibonacci
@: {n0: 0"1", n1: 1"1"};
def sign: $ -> \(<0..> 1! <> -1!\);
1..$*$sign -> $sign -> #
$@.n0!
<=1>
@: {n0: $@.n1, n1: $@.n0 + $@.n1};
<=-1>
@: {n0: $@.n1 - $@.n0, n1: $@.n0};
end nthFibonacci
</syntaxhighlight>

===State machine===
Instead of mutating state, we could just recurse internally on a state structure.
<syntaxhighlight lang="tailspin">
templates nthFibonacci
{ N: ($)"1", n0: 0"1", n1: 1"1" } -> #
when <{ N: <=0"1"> }> do
$.n0 !
when <{ N: <1"1"..>}> do
{ N: $.N - 1"1", n0: $.n1, n1: $.n0 + $.n1} -> #
otherwise
{ N: $.N + 1"1", n1: $.n0, n0: $.n1 - $.n0} -> #
end nthFibonacci
8 -> nthFibonacci -> '$;
' -> !OUT::write
-5 -> nthFibonacci -> '$;
' -> !OUT::write
-6 -> nthFibonacci -> '$;
' -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
21"1"
5"1"
-8"1"
</pre>


=={{header|Tcl}}==
=={{header|Tcl}}==
Line 9,638: Line 14,017:
====Iterative====
====Iterative====
{{trans|Perl}}
{{trans|Perl}}
<lang tcl>proc fibiter n {
<syntaxhighlight lang="tcl">proc fibiter n {
if {$n < 2} {return $n}
if {$n < 2} {return $n}
set prev 1
set prev 1
Line 9,646: Line 14,025:
}
}
return $fib
return $fib
}</lang>
}</syntaxhighlight>
====Recursive====
====Recursive====
<lang tcl>proc fib {n} {
<syntaxhighlight lang="tcl">proc fib {n} {
if {$n < 2} then {expr {$n}} else {expr {[fib [expr {$n-1}]]+[fib [expr {$n-2}]]} }
if {$n < 2} then {expr {$n}} else {expr {[fib [expr {$n-1}]]+[fib [expr {$n-2}]]} }
}</lang>
}</syntaxhighlight>


The following {{works with|Tcl|8.5}}: defining a procedure in the <code>::tcl::mathfunc</code> namespace allows that proc to be used as a function in <code>[http://www.tcl.tk/man/tcl8.5/TclCmd/expr.htm expr]</code> expressions.
The following {{works with|Tcl|8.5}}: defining a procedure in the <code>::tcl::mathfunc</code> namespace allows that proc to be used as a function in <code>[http://www.tcl.tk/man/tcl8.5/TclCmd/expr.htm expr]</code> expressions.
<lang tcl>proc tcl::mathfunc::fib {n} {
<syntaxhighlight lang="tcl">proc tcl::mathfunc::fib {n} {
if { $n < 2 } {
if { $n < 2 } {
return $n
return $n
Line 9,663: Line 14,042:
# or, more tersely
# or, more tersely


proc tcl::mathfunc::fib {n} {expr {$n<2 ? $n : fib($n-1) + fib($n-2)}}</lang>
proc tcl::mathfunc::fib {n} {expr {$n<2 ? $n : fib($n-1) + fib($n-2)}}</syntaxhighlight>


E.g.:
E.g.:


<lang tcl>expr {fib(7)} ;# ==> 13
<syntaxhighlight lang="tcl">expr {fib(7)} ;# ==> 13


namespace path tcl::mathfunc #; or, interp alias {} fib {} tcl::mathfunc::fib
namespace path tcl::mathfunc #; or, interp alias {} fib {} tcl::mathfunc::fib
fib 7 ;# ==> 13</lang>
fib 7 ;# ==> 13</syntaxhighlight>


====Tail-Recursive====
====Tail-Recursive====
In Tcl 8.6 a ''tailcall'' function is available to permit writing tail-recursive functions in Tcl. This makes deeply recursive functions practical. The availability of large integers also means no truncation of larger numbers.
In Tcl 8.6 a ''tailcall'' function is available to permit writing tail-recursive functions in Tcl. This makes deeply recursive functions practical. The availability of large integers also means no truncation of larger numbers.
<lang tcl>proc fib-tailrec {n} {
<syntaxhighlight lang="tcl">proc fib-tailrec {n} {
proc fib:inner {a b n} {
proc fib:inner {a b n} {
if {$n < 1} {
if {$n < 1} {
Line 9,685: Line 14,064:
}
}
return [fib:inner 0 1 $n]
return [fib:inner 0 1 $n]
}</lang>
}</syntaxhighlight>
% fib-tailrec 100
% fib-tailrec 100
354224848179261915075
354224848179261915075
Line 9,691: Line 14,070:
===Handling Negative Numbers===
===Handling Negative Numbers===
====Iterative====
====Iterative====
<lang tcl>proc fibiter n {
<syntaxhighlight lang="tcl">proc fibiter n {
if {$n < 0} {
if {$n < 0} {
set n [expr {abs($n)}]
set n [expr {abs($n)}]
Line 9,707: Line 14,086:
}
}
fibiter -5 ;# ==> 5
fibiter -5 ;# ==> 5
fibiter -6 ;# ==> -8</lang>
fibiter -6 ;# ==> -8</syntaxhighlight>
====Recursive====
====Recursive====
<lang tcl>proc tcl::mathfunc::fib {n} {expr {$n<-1 ? -1**($n+1) * fib(abs($n)) : $n<2 ? $n : fib($n-1) + fib($n-2)}}
<syntaxhighlight lang="tcl">proc tcl::mathfunc::fib {n} {expr {$n<-1 ? -1**($n+1) * fib(abs($n)) : $n<2 ? $n : fib($n-1) + fib($n-2)}}
expr {fib(-5)} ;# ==> 5
expr {fib(-5)} ;# ==> 5
expr {fib(-6)} ;# ==> -8</lang>
expr {fib(-6)} ;# ==> -8</syntaxhighlight>
===For the Mathematically Inclined===
===For the Mathematically Inclined===
This works up to <math>fib(70)</math>, after which the limited precision of IEEE double precision floating point arithmetic starts to show.<br>
This works up to <math>fib(70)</math>, after which the limited precision of IEEE double precision floating point arithmetic starts to show.<br>
{{works with|Tcl|8.5}}
{{works with|Tcl|8.5}}
<lang tcl>proc fib n {expr {round((.5 + .5*sqrt(5)) ** $n / sqrt(5))}}</lang>
<syntaxhighlight lang="tcl">proc fib n {expr {round((.5 + .5*sqrt(5)) ** $n / sqrt(5))}}</syntaxhighlight>


=={{header|TI-83 BASIC}}==
=={{header|Tern}}==
Iterative:
<lang ti83b>{0,1
While 1
Disp Ans(1
{Ans(2),sum(Ans
End</lang>


Binet's formula:
<lang ti83b>Prompt N
.5(1+√(5 //golden ratio
(Ans^N–(-Ans)^-N)/√(5</lang>

=={{header|TI-89 BASIC}}==
===Recursive===
===Recursive===
<syntaxhighlight lang="tern">func fib(n) {
Optimized implementation (too slow to be usable for ''n'' higher than about 12).
if (n < 2) {
return 1;
}
return fib(n - 1) + fib(n - 2);
}</syntaxhighlight>


===Coroutine===
<lang ti89b>fib(n)
<syntaxhighlight lang="tern">func fib(n) {
when(n<2, n, fib(n-1) + fib(n-2))</lang>
let a = 1;
let b = 2;
until(n-- <= 0) {
yield a;
(a, b) = (b, a + b);
}
}</syntaxhighlight>


=={{header|TI SR-56}}==
===Iterative===
Unoptimized implementation (I think the for loop can be eliminated, but I'm not sure).


{| class="wikitable"
<lang ti89b>fib(n)
|+ Texas Instruments SR-56 Program Listing for "Fibonacci Sequence"
Func
|-
Local a,b,c,i
! Display !! Key !! Display !! Key !! Display !! Key !! Display !! Key
0→a
|-
1→b
| 00 33 || STO || 25 || || 50 || || 75 ||
For i,1,n
|-
a→c
| 01 00 || 0 || 26 || || 51 || || 76 ||
b→a
|-
c+b→b
| 02 01 || 1 || 27 || || 52 || || 77 ||
EndFor
|-
a
| 03 33 || STO || 28 || || 53 || || 78 ||
EndFunc</lang>
|-
| 04 01 || 1 || 29 || || 54 || || 79 ||
|-
| 05 00 || 0 || 30 || || 55 || || 80 ||
|-
| 06 84 || + || 31 || || 56 || || 81 ||
|-
| 07 39 || *EXC || 32 || || 57 || || 82 ||
|-
| 08 01 || 1 || 33 || || 58 || || 83 ||
|-
| 09 94 || = || 34 || || 59 || || 84 ||
|-
| 10 27 || *dsz || 35 || || 60 || || 85 ||
|-
| 11 00 || 0 || 36 || || 61 || || 86 ||
|-
| 12 06 || 6 || 37 || || 62 || || 87 ||
|-
| 13 41 || R/S || 38 || || 63 || || 88 ||
|-
| 14 22 || GTO || 39 || || 64 || || 89 ||
|-
| 15 00 || 0 || 40 || || 65 || || 90 ||
|-
| 16 06 || 6 || 41 || || 66 || || 91 ||
|-
| 17 || || 42 || || 67 || || 92 ||
|-
| 18 || || 43 || || 68 || || 93 ||
|-
| 19 || || 44 || || 69 || || 94 ||
|-
| 20 || || 45 || || 70 || || 95 ||
|-
| 21 || || 46 || || 71 || || 96 ||
|-
| 22 || || 47 || || 72 || || 97 ||
|-
| 23 || || 48 || || 73 || || 98 ||
|-
| 24 || || 49 || || 74 || || 99 ||
|}


Asterisk denotes 2nd function key.
=={{header|TSE SAL}}==
<lang TSE SAL>


{| class="wikitable"
|+ Register allocation
|-
| 0: Nth term requested || 1: Last term || 2: Unused || 3: Unused || 4: Unused
|-
| 5: Unused || 6: Unused || 7: Unused || 8: Unused || 9: Unused
|}

Annotated listing:
<syntaxhighlight lang="text">
STO 0 // Nth term requested := User input
1 STO 1 // Last term := 1
0 // Initial value: 0
+ *EXC 1 = // Calculate next term.
*dsz 0 6 // Loop while R0 positive
R/S // Done, show answer
GTO 0 6 // If user hits R/S calculate next term
</syntaxhighlight>

'''Usage:'''

At the keypad enter a number N, then press RST R/S to calculate and display the Nth Fibonacci number. R/S for the following numbers.

{{in}}
<pre>1 RST R/S</pre>

{{out}}
<pre>1</pre>

{{in}}
<pre>2 RST R/S</pre>

{{out}}
<pre>1</pre>

{{in}}
<pre>3 RST R/S</pre>

{{out}}
<pre>2</pre>

{{in}}
<pre>10 RST R/S</pre>

{{out}}
<pre>55</pre>
<pre>R/S -> 89</pre>
<pre>R/S -> 144</pre>

=={{header|TI-57}}==
{| class="wikitable"
! Step
! Function
! Comment
|-
| 00
| align="center" | <code>STO</code> <code> 0 </code>
| R0 = n
|-
| 01
|align="center" | <code>C.t</code>
| R7 = 0
|-
| 02
|align="center" | <code> 1 </code>
| Display = 1
|-
| 03
|align="center" | <code>INV</code> <code>SUM</code> <code> 1 </code>
| R0 -= 1
|-
| 04
|align="center" | <code>Lbl</code> <code> 1 </code>
| loop
|-
| 05
|align="center" | <code> + </code>
|
|-
| 06
|align="center" | <code>x⮂t</code>
| Swap Display with R7
|-
| 07
|align="center" | <code> = </code>
| Display += R7
|-
| 08
|align="center" | <code>Dsz</code>
| R0 -= 1
|-
| 09
|align="center" | <code>GTO</code> <code>1</code>
| until R0 == 0
|-
| 10
|align="center" | <code>R/S</code>
| Stop
|-
| 11
|align="center" | <code>RST</code>
| Go back to step 0
|-
|}
10 <code>RST</code> <code>R/S</code>
{{out}}
<pre>
55.
</pre>

=={{header|TSE SAL}}==
<syntaxhighlight lang="tse sal">
// library: math: get: series: fibonacci <description></description> <version control></version control> <version>1.0.0.0.3</version> <version control></version control> (filenamemacro=getmasfi.s) [<Program>] [<Research>] [kn, ri, su, 20-01-2013 22:04:02]
// library: math: get: series: fibonacci <description></description> <version control></version control> <version>1.0.0.0.3</version> <version control></version control> (filenamemacro=getmasfi.s) [<Program>] [<Research>] [kn, ri, su, 20-01-2013 22:04:02]
INTEGER PROC FNMathGetSeriesFibonacciI( INTEGER nI )
INTEGER PROC FNMathGetSeriesFibonacciI( INTEGER nI )
Line 9,800: Line 14,333:
UNTIL FALSE
UNTIL FALSE
END
END
</syntaxhighlight>

=={{header|Turing}}==
<syntaxhighlight lang="turing">% Recursive
function fibb (n: int) : int
if n < 2 then
result n
else
result fibb (n-1) + fibb (n-2)
end if
end fibb

% Iterative
function ifibb (n: int) : int
var a := 0
var b := 1
for : 1 .. n
a := a + b
b := a - b
end for
result a
end ifibb


for i : 0 .. 10
</lang>
put fibb (i) : 4, ifibb (i) : 4
end for</syntaxhighlight>


Output:<pre> 0 0
1 1
1 1
2 2
3 3
5 5
8 8
13 13
21 21
34 34
55 55</pre>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
ASK "What fibionacci number do you want?": searchfib=""
ASK "What fibionacci number do you want?": searchfib=""
Line 9,820: Line 14,388:
PRINT "fibionacci number ",n,"=",fib
PRINT "fibionacci number ",n,"=",fib
ENDLOOP
ENDLOOP
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 9,837: Line 14,405:
</pre>
</pre>


=={{header|UnixPipes}}==
=={{header|Uiua}}==
{{works with|Uiua|0.10.0-dev.1}}
{{incorrect|UnixPipes|There is a race between parallel commands. <code>tee last</code> might open and truncate the file before <code>cat last</code> opens it. Then <code>cat last</code> pipes the empty file to ''xargs'', and ''expr'' reports a syntax error, and the script hangs forever.}}
Simple recursive example with memoisation.

<syntaxhighlight lang="Uiua">
<lang bash>echo 1 |tee last fib ; tail -f fib | while read x
F ← |1 memo⟨+⊃(F-1)(F-2)|∘⟩<2.
do
F ⇡20
cat last | tee -a fib | xargs -n 1 expr $x + |tee last
</syntaxhighlight>
done</lang>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|bash|3}}
{{works with|bash|3}}
<lang bash>#!/bin/bash
<syntaxhighlight lang="bash">#!/bin/bash


a=0
a=0
Line 9,858: Line 14,426:
echo "F($n): $a"
echo "F($n): $a"
b=$(($a - $b))
b=$(($a - $b))
done</lang>
done</syntaxhighlight>


Recursive:
Recursive:
{{works with|bash|3}}
{{works with|bash|3}}


<lang bash>fib() {
<syntaxhighlight lang="bash">fib() {
local n=$1
local n=$1
[ $n -lt 2 ] && echo -n $n || echo -n $(( $( fib $(( n - 1 )) ) + $( fib $(( n - 2 )) ) ))
[ $n -lt 2 ] && echo -n $n || echo -n $(( $( fib $(( n - 1 )) ) + $( fib $(( n - 2 )) ) ))
}</lang>
}</syntaxhighlight>

=={{header|UnixPipes}}==
{{incorrect|UnixPipes|There is a race between parallel commands. <code>tee last</code> might open and truncate the file before <code>cat last</code> opens it. Then <code>cat last</code> pipes the empty file to ''xargs'', and ''expr'' reports a syntax error, and the script hangs forever.}}

<syntaxhighlight lang="bash">echo 1 |tee last fib ; tail -f fib | while read x
do
cat last | tee -a fib | xargs -n 1 expr $x + |tee last
done</syntaxhighlight>


=={{header|Ursa}}==
=={{header|Ursa}}==
{{trans|Python}}
{{trans|Python}}
===Iterative===
===Iterative===
<lang ursa>def fibIter (int n)
<syntaxhighlight lang="ursa">def fibIter (int n)
if (< n 2)
if (< n 2)
return n
return n
Line 9,882: Line 14,458:
end for
end for
return fib
return fib
end</lang>
end</syntaxhighlight>



=={{header|Ursala}}==
=={{header|Ursala}}==
All three methods are shown here, and all have unlimited precision.
All three methods are shown here, and all have unlimited precision.
<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#import nat
#import nat


Line 9,900: Line 14,475:
(mp..div^|\~& mp..sub+ ~~ @rlX mp..pow_ui)^lrlPGrrPX/~& -+
(mp..div^|\~& mp..sub+ ~~ @rlX mp..pow_ui)^lrlPGrrPX/~& -+
^\~& ^(~&,mp..sub/1.E0)+ mp..div\2.E0+ mp..add/1.E0,
^\~& ^(~&,mp..sub/1.E0)+ mp..div\2.E0+ mp..add/1.E0,
mp..sqrt+ ..grow/5.E0+-+-</lang>
mp..sqrt+ ..grow/5.E0+-+-</syntaxhighlight>
The analytical method uses arbitrary precision floating point
The analytical method uses arbitrary precision floating point
arithmetic from the mpfr library and then converts the result to
arithmetic from the mpfr library and then converts the result to
Line 9,906: Line 14,481:
always chosen based on the argument. This test program computes the first
always chosen based on the argument. This test program computes the first
twenty Fibonacci numbers by all three methods.
twenty Fibonacci numbers by all three methods.
<lang Ursala>#cast %nLL
<syntaxhighlight lang="ursala">#cast %nLL


examples = <.iterative_fib,recursive_fib,analytical_fib>* iota20</lang>
examples = <.iterative_fib,recursive_fib,analytical_fib>* iota20</syntaxhighlight>
output:
output:
<pre>
<pre>
Line 9,936: Line 14,511:
Generate n'th fib by using binary recursion
Generate n'th fib by using binary recursion


<lang v>[fib
<syntaxhighlight lang="v">[fib
[small?] []
[small?] []
[pred dup pred]
[pred dup pred]
[+]
[+]
binrec].</lang>
binrec].</syntaxhighlight>


=={{header|Vala}}==
=={{header|Vala}}==
Line 9,946: Line 14,521:
===Recursive===
===Recursive===
Using int, but could easily replace with double, long, ulong, etc.
Using int, but could easily replace with double, long, ulong, etc.
<lang vala>
<syntaxhighlight lang="vala">
int fibRec(int n){
int fibRec(int n){
if (n < 2)
if (n < 2)
Line 9,953: Line 14,528:
return fibRec(n - 1) + fibRec(n - 2);
return fibRec(n - 1) + fibRec(n - 2);
}
}
</syntaxhighlight>
</lang>


===Iterative===
===Iterative===
Using int, but could easily replace with double, long, ulong, etc.
Using int, but could easily replace with double, long, ulong, etc.
<lang vala>
<syntaxhighlight lang="vala">
int fibIter(int n){
int fibIter(int n){
if (n < 2)
if (n < 2)
Line 9,974: Line 14,549:
return cur;
return cur;
}
}
</syntaxhighlight>
</lang>


=={{header|VAX Assembly}}==
=={{header|VAX Assembly}}==
<lang VAX Assembly> 0000 0000 1 .entry main,0
<syntaxhighlight lang="vax assembly"> 0000 0000 1 .entry main,0
7E 7CFD 0002 2 clro -(sp) ;result buffer
7E 7CFD 0002 2 clro -(sp) ;result buffer
5E DD 0005 3 pushl sp ;pointer to buffer
5E DD 0005 3 pushl sp ;pointer to buffer
Line 10,011: Line 14,586:
1836311903
1836311903
$
$
</syntaxhighlight>
</lang>

=={{header|VBA}}==
Like Visual Basic .NET, but with keyword "Public" and type Long instead of Decimal:

<lang VBA>
Public Function Fib(n As Integer) As Long
Dim fib0, fib1, sum As Long
Dim i As Integer
fib0 = 0
fib1 = 1
For i = 1 To n
sum = fib0 + fib1
fib0 = fib1
fib1 = sum
Next
Fib = fib0
End Function
</lang>

The (slow) recursive version:

<lang VBA>
Public Function RFib(Term As Integer) As Long
If Term < 2 Then RFib = Term Else RFib = RFib(Term - 1) + RFib(Term - 2)
End Function
</lang>

=={{header|VBScript}}==
===Non-recursive, object oriented, generator===
Defines a generator class, with a default Get property. Uses Currency for larger-than-Long values. Tests for overflow and switches to Double. Overflow information also available from class.

====Class Definition:====
<lang vb>class generator
dim t1
dim t2
dim tn
dim cur_overflow
Private Sub Class_Initialize
cur_overflow = false
t1 = ccur(0)
t2 = ccur(1)
tn = ccur(t1 + t2)
end sub
public default property get generated
on error resume next

generated = ccur(tn)
if err.number <> 0 then
generated = cdbl(tn)
cur_overflow = true
end if
t1 = ccur(t2)
if err.number <> 0 then
t1 = cdbl(t2)
cur_overflow = true
end if
t2 = ccur(tn)
if err.number <> 0 then
t2 = cdbl(tn)
cur_overflow = true
end if
tn = ccur(t1+ t2)
if err.number <> 0 then
tn = cdbl(t1) + cdbl(t2)
cur_overflow = true
end if
on error goto 0
end property
public property get overflow
overflow = cur_overflow
end property
end class</lang>

====Invocation:====
<lang vb>dim fib
set fib = new generator
dim i
for i = 1 to 100
wscript.stdout.write " " & fib
if fib.overflow then
wscript.echo
exit for
end if
next</lang>

====Output:====
<lang vbscript> 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 12586269025 20365011074 32951280099 53316291173 86267571272 139583862445 225851433717 365435296162 591286729879 956722026041 1548008755920 2504730781961 4052739537881 6557470319842 10610209857723 17167680177565 27777890035288 44945570212853 72723460248141 117669030460994 190392490709135 308061521170129 498454011879264 806515533049393</lang>


=={{header|Vedit macro language}}==
=={{header|Vedit macro language}}==
'''Iterative'''
===Iterative===

Calculate fibonacci(#1). Negative values return 0.
Calculate fibonacci(#1). Negative values return 0.
<lang vedit>:FIBONACCI:
<syntaxhighlight lang="vedit">:FIBONACCI:
#11 = 0
#11 = 0
#12 = 1
#12 = 1
Line 10,116: Line 14,599:
#12 = #10
#12 = #10
}
}
Return(#11)</lang>
Return(#11)</syntaxhighlight>


===Unlimited precision===
=={{header|Visual Basic}}==
<syntaxhighlight lang="vedit">// Fibonacci, unlimited precision.
{{works with|Visual Basic|VB6 Standard}}
// input: #1 = n
Maximum integer value (7*10^28) can be obtained by using decimal type, but decimal type is only a sub type of the variant type.
<lang vb>Sub fibonacci()
// return: fibonacci(n) in text register 10
//
Const n = 139
:fibo_unlimited:
Dim i As Integer
if (#1 < 2) {
Dim f1 As Variant, f2 As Variant, f3 As Variant 'for Decimal
Num_Str(#1, 10)
f1 = CDec(0): f2 = CDec(1) 'for Decimal setting
return
Debug.Print "fibo("; 0; ")="; f1
} else {
Debug.Print "fibo("; 1; ")="; f2
Buf_Switch(Buf_Free)
For i = 2 To n
IC('0') IN
f3 = f1 + f2
IC('1') IN
Debug.Print "fibo("; i; ")="; f3
f1 = f2
#10 = #1
f2 = f3
While (#10 > 1) {
#12 = 0 // carry out
Next i
#15 = 1 // column (ones, tens, hundreds...)
End Sub 'fibonacci</lang>
Repeat (ALL) { // Sum all columns
{{Out}}
Line(-1) // n-1
<pre>fibo( 0 )= 0
Goto_col(#15)
fibo( 1 )= 1
if (At_EOL) { // all digits added
fibo( 2 )= 1
break
...
}
fibo( 137 )= 19134702400093278081449423917
#11 = Cur_Char - '0' + #12 // digit of (n-1) + carry
fibo( 138 )= 30960598847965113057878492344
Line(-1) // n-2
fibo( 139 )= 50095301248058391139327916261 </pre>
Goto_Col(#15)
if (!At_EOL) { // may contain fewer digits than n-1
#11 += Cur_Char - '0'
}
Goto_Line(3) // sum
EOL
#12 = #11 / 10 // carry out
Ins_Char((#11 % 10) + '0')
#15++ // next column
}
if (#12) {
Goto_Line(3)
EOL
Ins_Char(#12 + '0') // any extra digit from carry
}
BOF
Del_Line(1) // Next n
Line(1) EOL
Ins_Newline
#10--
}
Goto_Line(2) // Results on line 2
}
// Copy the results to text register 10 in reverse order
Reg_Empty(10)
While(!At_EOL) {
Reg_Copy_Block(10, CP, CP+1, INSERT)
Char()
}
Buf_Quit(OK)
return</syntaxhighlight>

Test:
<syntaxhighlight lang="vedit">#1 = Get_Num("n: ", STATLINE)
Ins_Text("fibonacci(") Num_Ins(#1, LEFT+NOCR) Ins_Text(") = ")
Call("fibo_unlimited")
Reg_Ins(10) IN
return</syntaxhighlight>

{{out}}
<pre>fibonacci(1000) = 43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875</pre>


=={{header|Visual Basic .NET}}==
=={{header|V (Vlang)}}==
Update V (Vlang) to version 0.2.2
'''Platform:''' [[.NET]]
===Iterative===
===Iterative===
<syntaxhighlight lang="go">fn fib_iter(n int) int {
{{works with|Visual Basic .NET|9.0+}}
if n < 2 {
With Decimal type, maximum value is fibo(139).
return n
<lang vbnet>Function Fib(ByVal n As Integer) As Decimal
}
Dim fib0, fib1, sum As Decimal

Dim i As Integer
fib0 = 0
mut prev, mut fib := 0, 1
fib1 = 1
for _ in 0..(n - 1){
For i = 1 To n
prev, fib = fib, prev + fib
}
sum = fib0 + fib1
return fib
fib0 = fib1
}
fib1 = sum

Next
fn main() {
Fib = fib0
for val in 0..11 {
End Function</lang>
println('fibonacci(${val:2d}) = ${fib_iter(val):3d}')
}
}</syntaxhighlight>

===Recursive===
===Recursive===
<syntaxhighlight lang="go">fn fib_rec(n int) int {
{{works with|Visual Basic .NET|9.0+}}
if n < 2 {
<lang vbnet>Function Seq(ByVal Term As Integer)
return n
If Term < 2 Then Return Term
}
Return Seq(Term - 1) + Seq(Term - 2)
return fib_rec(n - 2) + fib_rec(n - 1)
End Function</lang>
}
===BigInteger===
There is no real maximum value of BigInterger class, except the memory to store the number.
Within a minute, fibo(2000000) is a number with 417975 digits.
<lang vbnet> Function FiboBig(ByVal n As Integer) As BigInteger
' Fibonacci sequence with BigInteger
Dim fibn2, fibn1, fibn As BigInteger
Dim i As Integer
fibn = 0
fibn2 = 0
fibn1 = 1
If n = 0 Then
Return fibn2
ElseIf n = 1 Then
Return fibn1
ElseIf n >= 2 Then
For i = 2 To n
fibn = fibn2 + fibn1
fibn2 = fibn1
fibn1 = fibn
Next i
Return fibn
End If
Return 0
End Function 'FiboBig


fn main() {
Sub fibotest()
for val in 0..11 {
Dim i As Integer, s As String
println('fibonacci(${val:2d}) = ${fib_rec(val):3d}')
i = 2000000 ' 2 millions
}
s = FiboBig(i).ToString
}
Console.WriteLine("fibo(" & i & ")=" & s & " - length=" & Len(s))
</syntaxhighlight>
End Sub 'fibotest</lang>
{{out}}
<pre>fibonacci( 0) = 0
fibonacci( 1) = 1
fibonacci( 2) = 1
fibonacci( 3) = 2
fibonacci( 4) = 3
fibonacci( 5) = 5
fibonacci( 6) = 8
fibonacci( 7) = 13
fibonacci( 8) = 21
fibonacci( 9) = 34
fibonacci(10) = 55
</pre>


=={{header|Wart}}==
=={{header|Wart}}==


===Recursive, all at once===
===Recursive, all at once===
<lang python>def (fib n)
<syntaxhighlight lang="python">def (fib n)
if (n < 2)
if (n < 2)
n
n
(+ (fib n-1) (fib n-2))</lang>
(+ (fib n-1) (fib n-2))</syntaxhighlight>


===Recursive, using cases===
===Recursive, using cases===
<lang python>def (fib n)
<syntaxhighlight lang="python">def (fib n)
(+ (fib n-1) (fib n-2))
(+ (fib n-1) (fib n-2))


def (fib n) :case (n < 2)
def (fib n) :case (n < 2)
n</lang>
n</syntaxhighlight>


===Recursive, using memoization===
===Recursive, using memoization===
<lang python>def (fib n saved)
<syntaxhighlight lang="python">def (fib n saved)
# all args in Wart are optional, and we expect callers to not provide `saved`
# all args in Wart are optional, and we expect callers to not provide `saved`
default saved :to (table 0 0 1 1) # pre-populate base cases
default saved :to (table 0 0 1 1) # pre-populate base cases
default saved.n :to
default saved.n :to
(+ (fib n-1 saved) (fib n-2 saved))
(+ (fib n-1 saved) (fib n-2 saved))
saved.n</lang>
saved.n</syntaxhighlight>


=={{header|WDTE}}==
=={{header|WDTE}}==


===Memoized Recursive===
===Memoized Recursive===
<lang WDTE>let memo fib n => switch n {
<syntaxhighlight lang="wdte">let memo fib n => n { > 1 => + (fib (- n 1)) (fib (- n 2)) };</syntaxhighlight>
== 0 => 0; == 1 => 1;
default => + (fib (- n 1)) (fib (- n 2));
};</lang>


===Iterative===
===Iterative===
<lang WDTE>let s => import 'stream';
<syntaxhighlight lang="wdte">let s => import 'stream';
let a => import 'arrays';
let a => import 'arrays';


Line 10,240: Line 14,755:
-> a.at 1
-> a.at 1
;
;
);</lang>
);</syntaxhighlight>

=={{header|WebAssembly}}==

<syntaxhighlight lang=wat>(func $fibonacci_nth (param $n i32) (result i32)

;;Declare some local registers
(local $i i32)
(local $a i32)
(local $b i32)
;;Handle first 2 numbers as special cases
(if (i32.eq (get_local $n) (i32.const 0))
(return (i32.const 0))
)
(if (i32.eq (get_local $n) (i32.const 1))
(return (i32.const 1))
)
;;Initialize first two values
(set_local $i (i32.const 1))
(set_local $a (i32.const 0))
(set_local $b (i32.const 1))
(block
(loop
;;Add two previous numbers and store the result
local.get $a
local.get $b
i32.add
(set_local $a (get_local $b))
set_local $b
;;Increment counter i by one
(set_local $i
(i32.add
(get_local $i)
(i32.const 1)
)
)
;;Check if loop is done
(br_if 1 (i32.ge_u (get_local $i) (get_local $n)))
(br 0)
)
)
;;The result is stored in b, so push that to the stack
get_local $b
)</syntaxhighlight>


=={{header|Whitespace}}==
=={{header|Whitespace}}==
Line 10,246: Line 14,810:
===Iterative===
===Iterative===
This program generates Fibonacci numbers until it is [http://ideone.com/VBDLzk forced to terminate].
This program generates Fibonacci numbers until it is [http://ideone.com/VBDLzk forced to terminate].
<syntaxhighlight lang="whitespace">
<lang Whitespace>


Line 10,258: Line 14,822:
</lang>
</syntaxhighlight>


It was generated from the following pseudo-Assembly.
It was generated from the following pseudo-Assembly.
<lang asm>push 0
<syntaxhighlight lang="asm">push 0
push 1
push 1


Line 10,272: Line 14,836:
copy 1
copy 1
add
add
jump 0</lang>
jump 0</syntaxhighlight>
{{out}}
{{out}}
<pre>$ wspace fib.ws | head -n 6
<pre>$ wspace fib.ws | head -n 6
Line 10,285: Line 14,849:


This program takes a number ''n'' on standard input and outputs the ''n''th member of the Fibonacci sequence.
This program takes a number ''n'' on standard input and outputs the ''n''th member of the Fibonacci sequence.
<syntaxhighlight lang="whitespace">
<lang Whitespace>
Line 10,313: Line 14,877:


</lang>
</syntaxhighlight>
<lang asm>; Read n.
<syntaxhighlight lang="asm">; Read n.
push 0
push 0
dup
dup
Line 10,342: Line 14,906:
add ; Leave the sum on the stack.
add ; Leave the sum on the stack.
1:
1:
ret</lang>
ret</syntaxhighlight>


{{out}}
{{out}}
Line 10,350: Line 14,914:
=={{header|Wrapl}}==
=={{header|Wrapl}}==
===Generator===
===Generator===
<lang wrapl>DEF fib() (
<syntaxhighlight lang="wrapl">DEF fib() (
VAR seq <- [0, 1]; EVERY SUSP seq:values;
VAR seq <- [0, 1]; EVERY SUSP seq:values;
REP SUSP seq:put(seq:pop + seq[1])[-1];
REP SUSP seq:put(seq:pop + seq[1])[-1];
);</lang>
);</syntaxhighlight>
To get the 17th number:
To get the 17th number:
<lang wrapl>16 SKIP fib();</lang>
<syntaxhighlight lang="wrapl">16 SKIP fib();</syntaxhighlight>
To get the list of all 17 numbers:
To get the list of all 17 numbers:
<lang wrapl>ALL 17 OF fib();</lang>
<syntaxhighlight lang="wrapl">ALL 17 OF fib();</syntaxhighlight>
===Iterator===
===Iterator===
Using type match signature to ensure integer argument:
Using type match signature to ensure integer argument:
<lang wrapl>TO fib(n @ Integer.T) (
<syntaxhighlight lang="wrapl">TO fib(n @ Integer.T) (
VAR seq <- [0, 1];
VAR seq <- [0, 1];
EVERY 3:to(n) DO seq:put(seq:pop + seq[1]);
EVERY 3:to(n) DO seq:put(seq:pop + seq[1]);
RET seq[-1];
RET seq[-1];
);</lang>
);</syntaxhighlight>

=={{header|Wren}}==
<syntaxhighlight lang="wren">// iterative (quick)
var fibItr = Fn.new { |n|
if (n < 2) return n
var a = 0
var b = 1
for (i in 2..n) {
var c = a + b
a = b
b = c
}
return b
}

// recursive (slow)
var fibRec
fibRec = Fn.new { |n|
if (n < 2) return n
return fibRec.call(n-1) + fibRec.call(n-2)
}

System.print("Iterative: %(fibItr.call(36))")
System.print("Recursive: %(fibRec.call(36))")</syntaxhighlight>

{{out}}
<pre>
Iterative: 14930352
Recursive: 14930352
</pre>


=={{header|x86 Assembly}}==
=={{header|x86 Assembly}}==
{{Works with|MASM}}
{{Works with|MASM}}
<lang asm>TITLE i hate visual studio 4 (Fibs.asm)
<syntaxhighlight lang="asm">TITLE i hate visual studio 4 (Fibs.asm)
; __ __/--------\
; __ __/--------\
; >__ \ / | |\
; >__ \ / | |\
Line 10,418: Line 15,012:
main ENDP
main ENDP


END main</lang>
END main</syntaxhighlight>


=={{header|xEec}}==
=={{header|xEec}}==
This will display the first 93 numbers of the sequence.
This will display the first 93 numbers of the sequence.
<syntaxhighlight lang="xeec">
<lang xEec>
h#1 h#1 h#1 o#
h#1 h#1 h#1 o#
h#10 o$ p
h#10 o$ p
Line 10,430: Line 15,024:
t
t
jnf
jnf
</syntaxhighlight>
</lang>


=={{header|XLISP}}==
=={{header|XLISP}}==
===Analytic===
===Analytic===
Uses Binet's method, based on the golden ratio, which almost feels like cheating—but the task specification doesn't require any particular algorithm, and this one is straightforward and fast.
Uses Binet's method, based on the golden ratio, which almost feels like cheating—but the task specification doesn't require any particular algorithm, and this one is straightforward and fast.
<lang lisp>(DEFUN FIBONACCI (N)
<syntaxhighlight lang="lisp">(DEFUN FIBONACCI (N)
(FLOOR (+ (/ (EXPT (/ (+ (SQRT 5) 1) 2) N) (SQRT 5)) 0.5)))</lang>
(FLOOR (+ (/ (EXPT (/ (+ (SQRT 5) 1) 2) N) (SQRT 5)) 0.5)))</syntaxhighlight>
To test it, we'll define a <tt>RANGE</tt> function and ask for the first 50 numbers in the sequence:
To test it, we'll define a <tt>RANGE</tt> function and ask for the first 50 numbers in the sequence:
<lang lisp>(DEFUN RANGE (X Y)
<syntaxhighlight lang="lisp">(DEFUN RANGE (X Y)
(IF (<= X Y)
(IF (<= X Y)
(CONS X (RANGE (+ X 1) Y))))
(CONS X (RANGE (+ X 1) Y))))


(PRINT (MAPCAR FIBONACCI (RANGE 1 50)))</lang>
(PRINT (MAPCAR FIBONACCI (RANGE 1 50)))</syntaxhighlight>
{{out}}
{{out}}
<pre>(1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 12586269025)</pre>
<pre>(1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 12586269025)</pre>
Line 10,448: Line 15,042:
===Tail recursive===
===Tail recursive===
Alternatively, this approach is reasonably efficient:
Alternatively, this approach is reasonably efficient:
<lang lisp>(defun fibonacci (x)
<syntaxhighlight lang="lisp">(defun fibonacci (x)
(defun fib (a b n)
(defun fib (a b n)
(if (= n 2)
(if (= n 2)
Line 10,455: Line 15,049:
(if (< x 2)
(if (< x 2)
x
x
(fib 1 1 x) ) )</lang>
(fib 1 1 x) ) )</syntaxhighlight>

=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">func Fib1(N); \Return Nth Fibonacci number using iteration
int N;
int Fn, F0, F1;
[F0:= 0; F1:= 1; Fn:= N;
while N > 1 do
[Fn:= F0 + F1;
F0:= F1;
F1:= Fn;
N:= N-1;
];
return Fn;
];

func Fib2(N); \Return Nth Fibonacci number using recursion
int N;
return if N < 2 then N else Fib2(N-1) + Fib2(N-2);

int N;
[for N:= 0 to 20 do [IntOut(0, Fib1(N)); ChOut(0, ^ )];
CrLf(0);
for N:= 0 to 20 do [IntOut(0, Fib2(N)); ChOut(0, ^ )];
CrLf(0);
]</syntaxhighlight>

{{out}}
<pre>
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
</pre>


=={{header|XQuery}}==
=={{header|XQuery}}==
<lang xquery>declare function local:fib($n as xs:integer) as xs:integer {
<syntaxhighlight lang="xquery">declare function local:fib($n as xs:integer) as xs:integer {
if($n < 2)
if($n < 2)
then $n
then $n
else local:fib($n - 1) + local:fib($n - 2)
else local:fib($n - 1) + local:fib($n - 2)
};</lang>
};</syntaxhighlight>

=={{header|Z80 Assembly}}==
<syntaxhighlight lang="z80">; 8 bit version
; IN : a = n (n <= 13, otherwise overflows)
; OUT: a = FIB(n)

fib8: cp 2
ret c ; if n < 2 then done

ld b,a
dec b ; b = n - 1
ld c,0 ; F0
ld a,1 ; F1

f8_l: ld d,a
add a,c
ld c,d
djnz f8_l

ret
</syntaxhighlight>

8 bits only? That's so 80's!

Let's go 32 bits...

<syntaxhighlight lang="z80">; 32 bit version
; IN : a = n (n <= 47, otherwise overflows)
; OUT: hlh'l' = FIB(n)

fib32: ld l,a ; lower bytes in the alt set
ld h,0
exx ; now in regular set
ld hl,0
cp 2
ret c ; if n < 2 then done

dec a ; loopcount = n - 1
ld bc,0
exx ; now in alt set
ld bc,0
ld hl,1

f32_l: ld d,h
ld e,l
add hl,bc
ld b,d
ld c,e
exx ; now in reg set
ld d,h
ld e,l
adc hl,bc
ld b,d
ld c,e
exx ; now in alt set
dec a
jr nz,f32_l

exx ; now in reg set
ret</syntaxhighlight>

=={{header|YAMLScript}}==
<syntaxhighlight lang="yaml">
!yamlscript/v0

defn main(n=10):
loop [a 0, b 1, i 1]:
say: a
if (i < n):
recur: b, (a + b), (i + 1)
</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
A slight tweak to the task; creates a function that continuously generates fib numbers
A slight tweak to the task; creates a function that continuously generates fib numbers
<lang zkl>var fibShift=fcn(ab){ab.append(ab.sum()).pop(0)}.fp(L(0,1));</lang>
<syntaxhighlight lang="zkl">var fibShift=fcn(ab){ab.append(ab.sum()).pop(0)}.fp(L(0,1));</syntaxhighlight>
<pre>
<pre>
zkl: do(15){ fibShift().print(",") }
zkl: do(15){ fibShift().print(",") }
Line 10,474: Line 15,170:
610,987,1597,2584,4181,
610,987,1597,2584,4181,
</pre>
</pre>

=={{header|ZX Spectrum Basic}}==
====Iterative====
<lang zxbasic>10 REM Only positive numbers
20 LET n=10
30 LET n1=0: LET n2=1
40 FOR k=1 TO n
50 LET sum=n1+n2
60 LET n1=n2
70 LET n2=sum
80 NEXT k
90 PRINT n1</lang>

====Analytic====
<lang zxbasic>10 DEF FN f(x)=INT (0.5+(((SQR 5+1)/2)^x)/SQR 5)</lang>


[[Category:Arithmetic]]
[[Category:Arithmetic]]

Revision as of 10:28, 2 May 2024

Task
Fibonacci sequence
You are encouraged to solve this task according to the task description, using any language you may know.

The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively:

      F0 = 0 
      F1 = 1 
      Fn = Fn-1 + Fn-2, if n>1 


Task

Write a function to generate the   nth   Fibonacci number.

Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).

The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:

      Fn = Fn+2 - Fn+1, if n<0   

support for negative     n     in the solution is optional.


Related tasks


References



0815

%<:0D:>~$<:01:~%>=<:a94fad42221f2702:>~>
}:_s:{x{={~$x+%{=>~>x~-x<:0D:~>~>~^:_s:?

11l

Translation of: Python
F fib_iter(n)
   I n < 2
      R n
   V fib_prev = 1
   V fib = 1
   L 2 .< n
      (fib_prev, fib) = (fib, fib + fib_prev)
   R fib

L(i) 1..20
   print(fib_iter(i), end' ‘ ’)
print()
Output:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765

360 Assembly

For maximum compatibility, programs use only the basic instruction set.

using fullword integers

*        Fibonacci sequence    05/11/2014
*        integer (31 bits) = 10 decimals -> max fibo(46)
FIBONACC CSECT
         USING FIBONACC,R12    base register
SAVEAREA B     STM-SAVEAREA(R15) skip savearea
         DC    17F'0'          savearea
         DC    CL8'FIBONACC'   eyecatcher
STM      STM   R14,R12,12(R13) save previous context
         ST    R13,4(R15)      link backward
         ST    R15,8(R13)      link forward
         LR    R12,R15         set addressability
*        ----
         LA    R1,0            f(n-2)=0
         LA    R2,1            f(n-1)=1
         LA    R4,2            n=2 
         LA    R6,1            step
         LH    R7,NN           limit
LOOP     EQU   *               for n=2 to nn
         LR    R3,R2             f(n)=f(n-1)
         AR    R3,R1             f(n)=f(n-1)+f(n-2)
         CVD   R4,PW             n  convert binary to packed (PL8)
         UNPK  ZW,PW             packed (PL8) to zoned (ZL16)
         MVC   CW,ZW             zoned (ZL16) to  char (CL16)
         OI    CW+L'CW-1,X'F0'   zap sign
         MVC   WTOBUF+5(2),CW+14 output
         CVD   R3,PW             f(n) binary to packed decimal (PL8)
         MVC   ZN,EM             load mask
         ED    ZN,PW             packed dec (PL8) to char (CL20)
         MVC   WTOBUF+9(14),ZN+6 output
         WTO   MF=(E,WTOMSG)     write buffer
         LR    R1,R2             f(n-2)=f(n-1)
         LR    R2,R3             f(n-1)=f(n)
         BXLE  R4,R6,LOOP      endfor n
*        ----
         LM    R14,R12,12(R13) restore previous savearea pointer
         XR    R15,R15         return code set to 0
         BR    R14             return to caller
*        ----  DATA
NN       DC    H'46'           nn max n
PW       DS    PL8             15num
ZW       DS    ZL16
CW       DS    CL16
ZN       DS    CL20
*                  ' b 0 0 0 , 0 0 0 , 0 0 0 , 0 0 0 , 0 0 0'  15num
EM       DC    XL20'402020206B2020206B2020206B2020206B202120'  mask
WTOMSG   DS    0F
         DC    H'80',XL2'0000'
*                   fibo(46)=1836311903         
WTOBUF   DC    CL80'fibo(12)=1234567890'
         REGEQU
         END   FIBONACC
Output:
...
fibo(41)=   165,580,141
fibo(42)=   267,914,296
fibo(43)=   433,494,437
fibo(44)=   701,408,733
fibo(45)= 1,134,903,170
fibo(46)= 1,836,311,903

using packed decimals

*        Fibonacci sequence        31/07/2018
*        packed dec (PL8) = 15 decimals => max fibo(73)
FIBOWTOP CSECT
         USING  FIBOWTOP,R13       base register
         B      72(R15)            skip savearea
         DC     17F'0'             savearea
         SAVE   (14,12)            save previous context
         ST     R13,4(R15)         link backward
         ST     R15,8(R13)         link forward
         LR     R13,R15            set addressability
*        ----
         ZAP    FNM2,=P'0'         f(0)=0
         ZAP    FNM1,=P'1'         f(1)=1
         LA     R4,2               n=2 
         LA     R6,1               step
         LH     R7,NN              limit
LOOP     EQU    *                  for n=2 to nn
         ZAP    FN,FNM1              f(n)=f(n-2)
         AP     FN,FNM2              f(n)=f(n-1)+f(n-2)
         CVD    R4,PW                n 
         MVC    ZN,EM                load mask
         ED     ZN,PW                packed dec (PL8) to char (CL16)
         MVC    WTOBUF+5(2),ZN+L'ZN-2  output
         MVC    ZN,EM                load mask
         ED     ZN,FN                packed dec (PL8) to char (CL16)
         MVC    WTOBUF+9(L'ZN),ZN        output
         WTO    MF=(E,WTOMSG)        write buffer
         ZAP    FNM2,FNM1            f(n-2)=f(n-1)
         ZAP    FNM1,FN              f(n-1)=f(n)
         BXLE   R4,R6,LOOP         endfor n
*        ----
         L      R13,4(0,R13)       restore previous savearea pointer
         RETURN (14,12),RC=0       restore registers from calling sav
*        ----   DATA
NN       DC     H'73'              nn
FNM2     DS     PL8                f(n-2)
FNM1     DS     PL8                f(n-1)
FN       DS     PL8                f(n)
PW       DS     PL8                15num
ZN       DS     CL20
*                   ' b 0 0 0 , 0 0 0 , 0 0 0 , 0 0 0 , 0 0 0'  15num
EM       DC     XL20'402020206B2020206B2020206B2020206B202120'  mask
WTOMSG   DS     0F
         DC     H'80',XL2'0000'
*                    fibo(73)=806515533049393
WTOBUF   DC     CL80'fibo(12)=123456789012345 '
         REGEQU  
         END    FIBOWTOP
Output:
...
fibo(68)=  72,723,460,248,141
fibo(69)= 117,669,030,460,994
fibo(70)= 190,392,490,709,135
fibo(71)= 308,061,521,170,129
fibo(72)= 498,454,011,879,264
fibo(73)= 806,515,533,049,393

6502 Assembly

This subroutine stores the first n—by default the first ten—Fibonacci numbers in memory, beginning (because, why not?) at address 3867 decimal = F1B hex. Intermediate results are stored in three sequential addresses within the low 256 bytes of memory, which are the most economical to access.

The results are calculated and stored, but are not output to the screen or any other physical device: how to do that would depend on the hardware and the operating system.

       LDA  #0
       STA  $F0     ; LOWER NUMBER
       LDA  #1
       STA  $F1     ; HIGHER NUMBER
       LDX  #0
LOOP:  LDA  $F1
       STA  $0F1B,X
       STA  $F2     ; OLD HIGHER NUMBER
       ADC  $F0
       STA  $F1     ; NEW HIGHER NUMBER
       LDA  $F2
       STA  $F0     ; NEW LOWER NUMBER
       INX
       CPX  #$0A    ; STOP AT FIB(10)
       BMI  LOOP
       RTS          ; RETURN FROM SUBROUTINE

68000 Assembly

Translation of: ARM Assembly

Input is in D0, and the output is also in D0. There is no protection from 32-bit overflow, so use at your own risk. (I used this C compiler to create this in ARM Assembly and translated it manually into 68000 Assembly. It wasn't that difficult since both CPUs have similar architectures.)

fib:
	MOVEM.L D4-D5,-(SP)
		MOVE.L D0,D4
		MOVEQ #0,D5
		CMP.L #2,D0
		BCS .bar
		MOVEQ #0,D5
.foo:
		MOVE.L D4,D0
		SUBQ.L #1,D0
		JSR fib
		SUBQ.L #2,D4
		ADD.L D0,D5
		CMP.L #1,D4
		BHI .foo
.bar:
		MOVE.L D5,D0
		ADD.L D4,D0
	MOVEM.L (SP)+,D4-D5
	RTS

8080 Assembly

This subroutine expects to be called with the value of in register A, and returns also in A. You may want to take steps to save the previous contents of B, C, and D. The routine only works with fairly small values of .

FIBNCI: MOV  C,  A  ; C will store the counter
        DCR  C      ; decrement, because we know f(1) already
        MVI  A,  1
        MVI  B,  0
LOOP:   MOV  D,  A
        ADD  B      ; A := A + B
        MOV  B,  D
        DCR  C
        JNZ  LOOP   ; jump if not zero
        RET         ; return from subroutine

The range may be easily be extended from the 13th (=233) to the 24th (=46368) Fibonacci number with 16-bit addition using DAD. The code here assumes the CP/M operating system.

	;-------------------------------------------------------
	; useful equates
	;-------------------------------------------------------
bdos	equ 	5	; BDOS entry 
cr	equ 	13	; ASCII carriage return
lf	equ 	10	; ASCII line feed
space	equ	32	; ASCII space char
conout	equ 	2	; BDOS console output function
putstr	equ	9	; BDOS print string function
nterms	equ	20	; number of terms (max=24) to display
	;-------------------------------------------------------
	; main code begins here
	;-------------------------------------------------------
	org	100h
	lxi	h,0		; save CP/M's stack
	dad	sp
	shld	oldstk
	lxi	sp,stack	; set our own stack
	lxi	d,signon	; print signon message
	mvi	c,putstr
	call	bdos
	mvi 	a,0		; start with Fib(0)
mloop:	push	a		; save our count	
	call 	fib
	call	putdec
	mvi	a,space		; separate the numbers
	call	putchr
	pop	a		; get our count back
	inr	a		; increment it
	cpi	nterms+1	; have we reached our limit?
	jnz	mloop		; no, keep going
	lhld	oldstk		; all done; get CP/M's stack back
	sphl			; restore it
	ret			; back to command processor
	;-------------------------------------------------------
	;  calculate nth Fibonacci number (max n = 24)
	;  entry: A = n 
	;  exit:  HL = Fib(n)
	;-------------------------------------------------------
fib:	mov 	c,a	; C holds n
	lxi 	d,0	; DE holds Fib(n-2)
	lxi 	h,1	; HL holds Fib(n-1)
	ana	a	; Fib(0) is a special case
	jnz	fib2	; n > 0 so calculate normally
	xchg		; otherwise return with HL=0
	ret
fib2:	dcr	c
	jz	fib3	; we're done
	push 	h	; save Fib(n-1)
	dad 	d	; HL = Fib(n), soon to be Fib(n-1) 
	pop 	d	; DE = old F(n-1), now Fib(n-2)
	jmp 	fib2	; ready for next pass
fib3:	ret
	;-------------------------------------------------------
	; console output of char in A register
	;-------------------------------------------------------
putchr:	push	h
	push	d
	push	b
	mov	e,a
	mvi	c,conout
	call	bdos
	pop	b
	pop	d
	pop	h
	ret
	;---------------------------------------------------------
	; Output decimal number to console
	; HL holds 16-bit unsigned binary number to print
	;---------------------------------------------------------
putdec: push	b
	push	d
	push	h
	lxi	b,-10
	lxi	d,-1
putdec2:
	dad	b
	inx	d
	jc	putdec2
	lxi	b,10
	dad	b
	xchg
	mov	a,h
	ora	l
	cnz	putdec		; recursive call
	mov	a,e
	adi	'0'
	call	putchr
	pop	h
	pop	d
	pop	b
	ret
	;-------------------------------------------------------
	; data area
	;-------------------------------------------------------
signon: db	'Fibonacci number sequence:',cr,lf,'$'
oldstk:	dw	0
stack	equ	$+128		; 64-level stack
	;
	end
Output:
Fibonacci number sequence:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765

8086 Assembly

Calculating the values at runtime

Is it cheating to write it in C for 64-bit x86 then port it to 16-bit x86?

The max input is 24 before you start having 16-bit overflow.

fib:
; 	WRITTEN IN C WITH X86-64 CLANG 3.3 AND DOWNGRADED TO 16-BIT X86
; 	INPUT: DI = THE NUMBER YOU WISH TO CALC THE FIBONACCI NUMBER FOR.
;	OUTPUTS TO AX
                                 
        push    BP
        push    BX
        push    AX
        mov     BX, DI			;COPY INPUT TO BX
        xor     AX, AX			;MOV AX,0
        test    BX, BX			;SET FLAGS ACCORDING TO BX
        je      LBB0_4			;IF BX == 0 RETURN 0
        cmp     BX, 1			;IF BX == 1 RETURN 1
        jne     LBB0_3
        mov     AX, 1			;ELSE, SET AX = 1 AND RETURN
        jmp     LBB0_4
LBB0_3:
        lea     DI, WORD PTR [BX - 1]   ;DI = BX - 1
        call    fib			;RETURN FIB(BX-1)
        mov     BP, AX			;STORE THIS IN BP
        add     BX, -2
        mov     DI, BX	
        call    fib			;GET FIB(DI - 2)
        add     AX, BP		        ;RETURN FIB(DI - 1) + FIB(DI - 2)
LBB0_4:

	add sp,2
        pop     BX
        pop     BP
        ret

Using A Lookup Table

With old computers it was common to use lookup tables to fetch pre-calculated values that would otherwise take some time to compute. The elements of the table are ordered by index, so you can simply create a function that takes an offset as the parameter and returns the element of the array at that offset.

Although lookup tables are very fast, there are some drawbacks to using them. For one, you end up taking up a lot of space. We're wasting a lot of bytes to store very low numbers at the beginning (each takes up 4 bytes regardless of how many digits you see). Unfortunately, when using lookup tables you have very little choice, since trying to conditionally change the scaling of the index would more than likely take more code than encoding all data as the maximum size regardless of the contents, as was done here. This keeps it simple for the CPU, which isn't aware of the intended size of each entry of the table.


For the purpose of this example, assume that both this code and the table are in the .CODE segment.

getfib:
;input: BX = the desired fibonacci number (in other words, the "n" in "F(n)")
;       DS must point to the segment where the fibonacci table is stored
;outputs to DX:AX (DX = high word, AX = low word)
  push ds
    cmp bx,41  ;bounds check
    ja IndexOutOfBounds
    shl bx,1
    shl bx,1 ;multiply by 4, since this is a table of dwords
    mov ax,@code
    mov ds,ax
    mov si,offset fib
    mov ax,[ds:si]    ;fetch the low word into AX
    mov dx,2[ds:si]   ;fetch the high word into DX
  pop ds
  ret


IndexOutOfBounds:
     stc             ;set carry to indicate an error
     mov ax,0FFFFh   ;return FFFF as the error code
   pop ds
   ret

;table of the first 41 fibonacci numbers
fib dword 0, 1, 1, 2, 3, 5, 8, 13 
    dword 21, 34, 55, 89, 144, 233, 377, 610
    dword 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657
    dword 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269
    dword 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986
    dword 102334155

8th

An iterative solution:

: fibon \ n -- fib(n)
  >r 0 1 
  ( tuck n:+ ) \ fib(n-2) fib(n-1) -- fib(n-1) fib(n)
  r> n:1- times ;

: fib \ n -- fib(n)
  dup 1 n:= if 1 ;; then
  fibon nip ;

ABAP

Iterative

FORM fibonacci_iter USING index TYPE i
                    CHANGING number_fib TYPE i.
  DATA: lv_old type i,
        lv_cur type i.
  Do index times.
    If sy-index = 1 or sy-index = 2.
      lv_cur = 1.
      lv_old = 0.
    endif.
    number_fib = lv_cur + lv_old.
    lv_old = lv_cur.
    lv_cur = number_fib.
  enddo.
ENDFORM.

Impure Functional

Works with: ABAP version 7.4 SP08 Or above only
cl_demo_output=>display( REDUCE #( INIT fibnm = VALUE stringtab( ( |0| ) ( |1| ) )
                                        n TYPE string
                                        x = `0`
                                        y = `1`
                                      FOR i = 1 WHILE i <= 100
                                     NEXT n = ( x + y )
                                          fibnm = VALUE #( BASE fibnm ( n ) )
                                          x = y
                                          y = n ) ).

ACL2

Fast, tail recursive solution:

(defun fast-fib-r (n a b)
   (if (or (zp n) (zp (1- n)))
       b
       (fast-fib-r (1- n) b (+ a b))))

(defun fast-fib (n)
   (fast-fib-r n 1 1))

(defun first-fibs-r (n i)
   (declare (xargs :measure (nfix (- n i))))
   (if (zp (- n i))
       nil
       (cons (fast-fib i)
             (first-fibs-r n (1+ i)))))

(defun first-fibs (n)
   (first-fibs-r n 0))
Output:
>(first-fibs 20)
(1 1 2 3 5 8 13 21 34 55 89
   144 233 377 610 987 1597 2584 4181 6765)

Action!

Action! language does not support recursion. Therefore an iterative approach has been proposed.

INT FUNC Fibonacci(INT n)
  INT curr,prev,tmp

  IF n>=-1 AND n<=1 THEN
    RETURN (n)
  FI

  prev=0
  IF n>0 THEN
    curr=1
    DO
      tmp=prev
      prev=curr
      curr==+tmp
      n==-1
    UNTIL n=1
    OD
  ELSE
    curr=-1
    DO
      tmp=prev
      prev=curr
      curr==+tmp
      n==+1
    UNTIL n=-1
    OD
  FI
RETURN (curr)

PROC Main()
  BYTE n
  INT f

  Put(125) ;clear screen

  FOR n=0 TO 22
  DO
    f=Fibonacci(n)
    Position(2,n+1)
    PrintF("Fib(%I)=%I",n,f)

    IF n>0 THEN
      f=Fibonacci(-n)
      Position(21,n+1)
      PrintF("Fib(%I)=%I",-n,f)
    FI
  OD
RETURN
Output:

Screenshot from Atari 8-bit computer

Fib(0)=0
Fib(1)=1           Fib(-1)=-1
Fib(2)=1           Fib(-2)=-1
Fib(3)=2           Fib(-3)=-2
Fib(4)=3           Fib(-4)=-3
Fib(5)=5           Fib(-5)=-5
Fib(6)=8           Fib(-6)=-8
Fib(7)=13          Fib(-7)=-13
Fib(8)=21          Fib(-8)=-21
Fib(9)=34          Fib(-9)=-34
Fib(10)=55         Fib(-10)=-55
Fib(11)=89         Fib(-11)=-89
Fib(12)=144        Fib(-12)=-144
Fib(13)=233        Fib(-13)=-233
Fib(14)=377        Fib(-14)=-377
Fib(15)=610        Fib(-15)=-610
Fib(16)=987        Fib(-16)=-987
Fib(17)=1597       Fib(-17)=-1597
Fib(18)=2584       Fib(-18)=-2584
Fib(19)=4181       Fib(-19)=-4181
Fib(20)=6765       Fib(-20)=-6765
Fib(21)=10946      Fib(-21)=-10946
Fib(22)=17711      Fib(-22)=-17711

ActionScript

public function fib(n:uint):uint
{
    if (n < 2)
        return n;
    
    return fib(n - 1) + fib(n - 2);
}

Ada

Recursive

with Ada.Text_IO, Ada.Command_Line;

procedure Fib is

   X: Positive := Positive'Value(Ada.Command_Line.Argument(1));

   function Fib(P: Positive) return Positive is
   begin
      if P <= 2 then
         return 1;
      else
         return Fib(P-1) + Fib(P-2);
      end if;
   end Fib;

begin
   Ada.Text_IO.Put("Fibonacci(" & Integer'Image(X) & " ) = ");
   Ada.Text_IO.Put_Line(Integer'Image(Fib(X)));
end Fib;

Iterative, build-in integers

with Ada.Text_IO;  use Ada.Text_IO;

procedure Test_Fibonacci is
   function Fibonacci (N : Natural) return Natural is
      This : Natural := 0;
      That : Natural := 1;
      Sum  : Natural;
   begin
      for I in 1..N loop
         Sum  := This + That;
         That := This;
         This := Sum;
      end loop;
      return This;
   end Fibonacci;
begin
   for N in 0..10 loop
      Put_Line (Positive'Image (Fibonacci (N)));
   end loop;
end Test_Fibonacci;
Output:
 0
 1
 1
 2
 3
 5
 8
 13
 21
 34
 55

Iterative, long integers

Using the big integer implementation from a cryptographic library [1].

with Ada.Text_IO, Ada.Command_Line, Crypto.Types.Big_Numbers;

procedure Fibonacci is

   X: Positive := Positive'Value(Ada.Command_Line.Argument(1));

   Bit_Length: Positive := 1 + (696 * X) / 1000;
   -- that number of bits is sufficient to store the full result.

   package LN is new Crypto.Types.Big_Numbers
     (Bit_Length + (32 - Bit_Length mod 32));
     -- the actual number of bits has to be a multiple of 32
   use LN;

   function Fib(P: Positive) return Big_Unsigned is
      Previous: Big_Unsigned := Big_Unsigned_Zero;
      Result:   Big_Unsigned := Big_Unsigned_One;
      Tmp:      Big_Unsigned;
   begin
      -- Result = 1 = Fibonacci(1)
      for I in 1 .. P-1 loop
         Tmp := Result;
         Result := Previous + Result;
         Previous := Tmp;
         -- Result = Fibonacci(I+1))
      end loop;
      return Result;
   end Fib;

begin
   Ada.Text_IO.Put("Fibonacci(" & Integer'Image(X) & " ) = ");
   Ada.Text_IO.Put_Line(LN.Utils.To_String(Fib(X)));
end Fibonacci;
Output:
> ./fibonacci 777
Fibonacci( 777 ) = 1081213530912648191985419587942084110095342850438593857649766278346130479286685742885693301250359913460718567974798268702550329302771992851392180275594318434818082

Fast method using fast matrix exponentiation

with ada.text_io;
use  ada.text_io;

procedure fast_fibo is 
	-- We work with biggest natural integers in a 64 bits machine 
	type Big_Int is mod 2**64;

	-- We provide an index type for accessing the fibonacci sequence terms 
	type Index is new Big_Int;

	-- fibo is a generic function that needs a modulus type since it will return
	-- the n'th term of the fibonacci sequence modulus this type (use Big_Int to get the	
	-- expected behaviour in this particular task)
	generic
		type ring_element is mod <>;
		with function "*" (a, b : ring_element) return ring_element is <>;
		function fibo (n : Index) return ring_element;
	function fibo (n : Index) return ring_element is

		type matrix is array (1 .. 2, 1 .. 2) of ring_element;

		-- f is the matrix you apply to a column containing (F_n, F_{n+1}) to get 
		-- the next one containing (F_{n+1},F_{n+2})
		-- could be a more general matrix (given as a generic parameter) to deal with 
		-- other linear sequences of order 2
		f : constant matrix := (1 => (0, 1), 2 => (1, 1));

		function "*" (a, b : matrix) return matrix is
		(1 => (a(1,1)*b(1,1)+a(1,2)*b(2,1), a(1,1)*b(1,2)+a(1,2)*b(2,2)),
		 2 => (a(2,1)*b(1,1)+a(2,2)*b(2,1), a(2,1)*b(1,2)+a(2,2)*b(2,2)));

		function square (m : matrix) return matrix is (m * m);

		-- Fast_Pow could be non recursive but it doesn't really matter since
		-- the number of calls is bounded up by the size (in bits) of Big_Int (e.g 64)
		function fast_pow (m : matrix; n : Index) return matrix is
		(if n = 0 then (1 => (1, 0), 2 => (0, 1)) -- = identity matrix
		 elsif n mod 2 = 0 then square (fast_pow (m, n / 2)) 
		 else m * square (fast_pow (m, n / 2)));

	begin
		return fast_pow (f, n)(2, 1);
	end fibo;

	function Big_Int_Fibo is new fibo (Big_Int);
begin
	-- calculate instantly F_n with n=10^15 (modulus 2^64 )
	put_line (Big_Int_Fibo (10**15)'img);
end fast_fibo;

AdvPL

Recursive

#include "totvs.ch"
User Function fibb(a,b,n)
return(if(--n>0,fibb(b,a+b,n),a))

Iterative

#include "totvs.ch"
User Function fibb(n) 
	local fnow:=0, fnext:=1, tempf
	while (--n>0)
		tempf:=fnow+fnext
		fnow:=fnext
		fnext:=tempf
	end while
return(fnext)

Agda

module FibonacciSequence where

open import Data.Nat using ( ; zero ; suc ; _+_)

rec_fib : (m : ) -> (a : ) -> (b : ) -> ℕ
rec_fib zero a b = a
rec_fib (suc k) a b = rec_fib k b (a + b)

fib : (n : ) -> ℕ
fib n = rec_fib n zero (suc zero)

Aime

integer
fibs(integer n)
{
    integer w;

    if (n == 0) {
        w = 0;
    } elif (n == 1) {
        w = 1;
    } else {
        integer a, b, i;

        i = 1;
        a = 0;
        b = 1;
        while (i < n) {
            w = a + b;
            a = b;
            b = w;
            i += 1;
        }
    }

    return w;
}

ALGOL 60

Works with: A60
begin
    comment Fibonacci sequence;
    integer procedure fibonacci(n); value n; integer n;
    begin
        integer i, fn, fn1, fn2;
        fn2 := 1;
        fn1 := 0;
        fn  := 0;
        for i := 1 step 1 until n do begin
            fn  := fn1 + fn2;
            fn2 := fn1;
            fn1 := fn
        end;
        fibonacci := fn
    end fibonacci;
 
    integer i;
    for i := 0 step 1 until 20 do outinteger(1,fibonacci(i))
end
Output:
 0  1  1  2  3  5  8  13  21  34  55  89  144  233  377  610  987  1597  2584  4181  6765


ALGOL 68

Analytic

Works with: ALGOL 68 version Revision 1 - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8-8d
PROC analytic fibonacci = (LONG INT n)LONG INT:(
  LONG REAL sqrt 5 = long sqrt(5);
  LONG REAL p = (1 + sqrt 5) / 2;
  LONG REAL q = 1/p;
  ROUND( (p**n + q**n) / sqrt 5 )
);

FOR i FROM 1 TO 30 WHILE
  print(whole(analytic fibonacci(i),0));
# WHILE # i /= 30 DO
  print(", ")
OD;
print(new line)
Output:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040

Iterative

Works with: ALGOL 68 version Revision 1 - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8-8d
PROC iterative fibonacci = (INT n)INT: 
  CASE n+1 IN
    0, 1, 1, 2, 3, 5
  OUT
    INT even:=3, odd:=5;
    FOR i FROM odd+1 TO n DO
      (ODD i|odd|even) := odd + even
    OD;
    (ODD n|odd|even)
  ESAC;

FOR i FROM 0 TO 30 WHILE
  print(whole(iterative fibonacci(i),0));
# WHILE # i /= 30 DO
  print(", ")
OD;
print(new line)
Output:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040

Recursive

Works with: ALGOL 68 version Revision 1 - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8-8d
PROC recursive fibonacci = (INT n)INT:
  ( n < 2 | n | fib(n-1) + fib(n-2));

Generative

Translation of: Python – Note: This specimen retains the original Python coding style.
Works with: ALGOL 68 version Revision 1 - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8-8d
MODE YIELDINT = PROC(INT)VOID;

PROC gen fibonacci = (INT n, YIELDINT yield)VOID: (
  INT even:=0, odd:=1;
  yield(even);
  yield(odd);
  FOR i FROM odd+1 TO n DO
    yield( (ODD i|odd|even) := odd + even )
  OD
);

main:(
  # FOR INT n IN # gen fibonacci(30, # ) DO ( #
  ##   (INT n)VOID:(
        print((" ",whole(n,0)))
  # OD # ));
    print(new line)
)
Output:
1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040

Array (Table) Lookup

Works with: ALGOL 68 version Revision 1 - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8-8d

This uses a pre-generated list, requiring much less run-time processor usage, but assumes that INT is only 31 bits wide.

[]INT const fibonacci = []INT( -1836311903, 1134903170,
  -701408733, 433494437, -267914296, 165580141, -102334155,
  63245986, -39088169, 24157817, -14930352, 9227465, -5702887,
  3524578, -2178309, 1346269, -832040, 514229, -317811, 196418,
  -121393, 75025, -46368, 28657, -17711, 10946, -6765, 4181,
  -2584, 1597, -987, 610, -377, 233, -144, 89, -55, 34, -21, 13,
  -8, 5, -3, 2, -1, 1, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
  144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711,
  28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040,
  1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817,
  39088169, 63245986, 102334155, 165580141, 267914296, 433494437,
  701408733, 1134903170, 1836311903
)[@-46];

PROC VOID value error := stop;

PROC lookup fibonacci = (INT i)INT: (
  IF LWB const fibonacci <= i AND i<= UPB const fibonacci THEN
    const fibonacci[i]
  ELSE
    value error; SKIP
  FI
);

FOR i FROM 0 TO 30 WHILE
  print(whole(lookup fibonacci(i),0));
# WHILE # i /= 30 DO
  print(", ")
OD;
print(new line)
Output:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040

ALGOL W

begin
    % return the nth Fibonacci number %
    integer procedure Fibonacci( integer value n ) ;
        begin
            integer fn, fn1, fn2;
            fn2 := 1;
            fn1 := 0;
            fn  := 0;
            for i := 1 until n do begin
                fn  := fn1 + fn2;
                fn2 := fn1;
                fn1 := fn
            end ;
            fn
        end Fibonacci ;

    for i := 0 until 10 do writeon( i_w := 3, s_w := 0, Fibonacci( i ) )

end.
Output:
  0  1  1  2  3  5  8 13 21 34 55

ALGOL-M

Note that the 21st Fibonacci number (= 10946) is the largest that can be calculated without overflowing ALGOL-M's integer data type.

Iterative

INTEGER FUNCTION FIBONACCI( X ); INTEGER X;
BEGIN
    INTEGER M, N, A, I;
    M := 0;
    N := 1;
    FOR I := 2 STEP 1 UNTIL X DO
    BEGIN
        A := N;
        N := M + N;
        M := A;
    END;
    FIBONACCI := N;
END;

Naively recursive

INTEGER FUNCTION FIBONACCI( X ); INTEGER X;
BEGIN
    IF X < 3 THEN
        FIBONACCI := 1
    ELSE
        FIBONACCI := FIBONACCI( X - 2 ) + FIBONACCI( X - 1 );
END;

Alore

def fib(n as Int) as Int
   if n < 2
      return 1
   end
   return fib(n-1) + fib(n-2)
end

Amazing Hopper

Analitic, Recursive and Iterative mode.

#include <hbasic.h>

#define TERM1    1.61803398874989
#define TERM2    -0.61803398874989

#context get Fibonacci number with analitic mode
  GetArgs(n) 
  get Inv of (M_SQRT5), Mul by( Pow (TERM 1, n), Minus( Pow(TERM 2, n) )  );
  then Return\\

#proto fibonacci_recursive(__X__)
#synon _fibonacci_recursive    getFibonaccinumberwithrecursivemodeof

#proto fibonacci_iterative(__X__)
#synon _fibonacci_iterative    getFibonaccinumberwithiterativemodeof

Begin
  Option Stack 1024

  get Arg Number(2, n), and Take( n );
  then, get Fibonacci number with analitic mode, and Print It with a Newl.
  secondly, get Fibonacci number with recursive mode of(n), and Print It with a Newl.
  finally, get Fibonacci number with iterative mode of (n), and Print It with a Newl.
End

Subrutines

fibonacci_recursive(n)
   Iif ( var(n) Is Le? (2), 1 , \
         get Fibonacci number with recursive mode of( var(n) Minus (1));\
         get Fibonacci number with recursive mode of( var(n) Minus (2)); and Add It )
Return

fibonacci_iterative(n)
  A=0
  B=1
  For Up( I:=2, n, 1 )
    C=B
    Let ( B: = var(A) Plus (B) )
    A=C
  Next
Return(B)
Output:
$ hopper src/fibo1.bas 25
75025
75025
75025

AntLang

/Sequence
fib:{<0;1> {x,<x[-1]+x[-2]>}/ range[x]}
/nth
fibn:{fib[x][x]}

Apex

/*
 author: snugsfbay
 date: March 3, 2016
 description: Create a list of x numbers in the Fibonacci sequence.
     - user may specify the length of the list 
     - enforces a minimum of 2 numbers in the sequence because any fewer is not a sequence
     - enforces a maximum of 47 because further values are too large for integer data type 
     - Fibonacci sequence always starts with 0 and 1 by definition
*/
public class FibNumbers{

final static Integer MIN = 2; //minimum length of sequence
final static Integer MAX = 47; //maximum length of sequence

/* 
  description: method to create a list of numbers in the Fibonacci sequence 
  param: user specified integer representing length of sequence should be 2-47, inclusive.
      - Sequence starts with 0 and 1 by definition so the minimum length could be as low as 2.
      - For 48th number in sequence or greater, code would require a Long data type rather than an Integer.
  return: list of integers in sequence.
*/
public static List<Integer> makeSeq(Integer len){

  List<Integer> fib = new List<Integer>{0,1}; // initialize list with first two values
  Integer i;
  
  if(len<MIN || len==null || len>MAX) {
      if (len>MAX){
          len=MAX; //set length to maximum if user entered too high a value
      }else{
          len=MIN; //set length to minimum if user entered too low a value or none
      }
  } //This could be refactored using teneray operator, but we want code coverage to be reflected for each condition
  
  //start with initial list size to find previous two values in the sequence, continue incrementing until list reaches user defined length
  for(i=fib.size(); i<len; i++){ 
    fib.add(fib[i-1]+fib[i-2]); //create new number based on previous numbers and add that to the list
  }

  return fib; 
  }
  
}

APL

Naive Recursive

Works with: Dyalog APL
fib{1:⍵  ( -1)+ -2}

Read this as: In the variable "fib", store the function that says, if the argument is less than or equal to 1, return the argument. Else, calculate the value you get when you recursively call the current function with the argument of the current argument minus one and add that to the value you get when you recursively call the current function with the argument of the current function minus two.

This naive solution requires Dyalog APL because GNU APL does not support this syntax for conditional guards.

Array

Works with: Dyalog APL
Works with: GNU APL

Since APL is an array language we'll use the following identity:

In APL:

↑+.×/N/2 21 1 1 0

Plugging in 4 for N gives the following result:

Here's what happens: We replicate the 2-by-2 matrix N times and then apply inner product-replication. The First removes the shell from the Enclose. At this point we're basically done, but we need to pick out only in order to complete the task. Here's one way:

0 1↓↑+.×/N/2 21 1 1 0

Analytic

Works with: Dyalog APL
Works with: GNU APL

An alternative approach, using Binet's formula (which was apparently known long before Binet):

.5+(((1+PHI)÷2)*⍳N)÷PHI5*.5

AppleScript

Imperative

set fibs to {}
set x to (text returned of (display dialog "What fibbonaci number do you want?" default answer "3"))
set x to x as integer
repeat with y from 1 to x
	if (y = 1 or y = 2) then
		copy 1 to the end of fibs
	else
		copy ((item (y - 1) of fibs) + (item (y - 2) of fibs)) to the end of fibs
	end if
end repeat
return item x of fibs


Functional

The simple recursive version is famously slow:

on fib(n)
    if n < 1 then
        0
    else if n < 3 then
        1
    else
        fib(n - 2) + fib(n - 1)
    end if
end fib

but we can combine enumFromTo(m, n) with the accumulator of a higher-order fold/reduce function to memoize the series:

Translation of: JavaScript

(ES6 memoized fold example)

Translation of: Haskell

(Memoized fold example)

-------------------- FIBONACCI SEQUENCE --------------------

-- fib :: Int -> Int
on fib(n)
    
    -- lastTwo : (Int, Int) -> (Int, Int)
    script lastTwo
        on |λ|([a, b])
            [b, a + b]
        end |λ|
    end script
    
    item 1 of foldl(lastTwo, {0, 1}, enumFromTo(1, n))
end fib


--------------------------- TEST ---------------------------
on run
    
    fib(32)
    
    --> 2178309
end run

-------------------- GENERIC FUNCTIONS ---------------------

-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
    if m  n then
        set lst to {}
        repeat with i from m to n
            set end of lst to i
        end repeat
        lst
    else
        {}
    end if
end enumFromTo

-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        repeat with i from 1 to lng
            set v to |λ|(v, item i of xs, i, xs)
        end repeat
        return v
    end tell
end foldl

-- Lift 2nd class handler function into 1st class script wrapper 
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn
Output:
2178309

Arendelle

( fibonacci , 1; 1 )

[ 98 , // 100 numbers of fibonacci

	( fibonacci[ @fibonacci? ] ,

		@fibonacci[ @fibonacci - 1 ] + @fibonacci[ @fibonacci - 2 ]

	)

	"Index: | @fibonacci? | => | @fibonacci[ @fibonacci? - 1 ] |"
]

ARM Assembly

Expects to be called with in R0, and will return in the same register.

fibonacci:
        push  {r1-r3}
        mov   r1,  #0
        mov   r2,  #1
        
fibloop:
        mov   r3,  r2
        add   r2,  r1,  r2
        mov   r1,  r3
        sub   r0,  r0,  #1
        cmp   r0,  #1
        bne   fibloop
        
        mov   r0,  r2
        pop   {r1-r3}
        mov   pc,  lr

ArnoldC

IT'S SHOWTIME

HEY CHRISTMAS TREE f1
YOU SET US UP @I LIED
TALK TO THE HAND f1

HEY CHRISTMAS TREE f2
YOU SET US UP @NO PROBLEMO

HEY CHRISTMAS TREE f3
YOU SET US UP @I LIED

STICK AROUND @NO PROBLEMO

GET TO THE CHOPPER f3
HERE IS MY INVITATION f1
GET UP f2
ENOUGH TALK
TALK TO THE HAND f3

GET TO THE CHOPPER f1
HERE IS MY INVITATION f2
ENOUGH TALK

GET TO THE CHOPPER f2
HERE IS MY INVITATION f3
ENOUGH TALK

CHILL

YOU HAVE BEEN TERMINATED

Arturo

Recursive

fib: $[x][
	if? x<2 [1]
	else [(fib x-1) + (fib x-2)]
]

loop 1..25 [x][
	print ["Fibonacci of" x "=" fib x]
]

AsciiDots

/--#$--\
|      |
>-*>{+}/
| \+-/
1  |
#  1
|  #
|  |
.  .

ATS

Recursive

fun fib_rec(n: int): int =
  if n >= 2 then fib_rec(n-1) + fib_rec(n-2) else n

Iterative

(*
** This one is also referred to as being tail-recursive 
*)
fun
fib_trec(n: int): int =
if
n > 0
then (fix loop (i:int, r0:int, r1:int): int => if i > 1 then loop (i-1, r1, r0+r1) else r1)(n, 0, 1)
else 0

Iterative and Verified

(*
** This implementation is verified!
*)

dataprop FIB (int, int) =
  | FIB0 (0, 0) | FIB1 (1, 1)
  | {n:nat} {r0,r1:int} FIB2 (n+2, r0+r1) of (FIB (n, r0), FIB (n+1, r1))
// end of [FIB] // end of [dataprop]

fun
fibats{n:nat}
  (n: int (n))
: [r:int] (FIB (n, r) | int r) = let
  fun loop
    {i:nat | i <= n}{r0,r1:int}
  (
    pf0: FIB (i, r0), pf1: FIB (i+1, r1)
  | ni: int (n-i), r0: int r0, r1: int r1
  ) : [r:int] (FIB (n, r) | int r) =
    if (ni > 0)
      then loop{i+1}(pf1, FIB2 (pf0, pf1) | ni - 1, r1, r0 + r1)
      else (pf0 | r0)
    // end of [if]
  // end of [loop]
in
  loop {0} (FIB0 (), FIB1 () | n, 0, 1)
end // end of [fibats]

Matrix-based

(* ****** ****** *)
//
// How to compile:
// patscc -o fib fib.dats
//
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
//
(* ****** ****** *)
//
abst@ype
int3_t0ype =
  (int, int, int)
//
typedef int3 = int3_t0ype
//
(* ****** ****** *)

extern
fun int3 : (int, int, int) -<> int3
extern
fun int3_1 : int3 -<> int
extern
fun mul_int3_int3: (int3, int3) -<> int3

(* ****** ****** *)

local

assume
int3_t0ype = (int, int, int)

in (* in-of-local *)
//
implement
int3 (x, y, z) = @(x, y, z)
//
implement int3_1 (xyz) = xyz.1
//
implement
mul_int3_int3
(
  @(a,b,c), @(d,e,f)
) =
  (a*d + b*e, a*e + b*f, b*e + c*f)
//
end // end of [local]

(* ****** ****** *)
//
implement
gnumber_int<int3> (n) = int3(n, 0, n)
//
implement gmul_val<int3> = mul_int3_int3
//
(* ****** ****** *)
//
fun
fib (n: intGte(0)): int =
  int3_1(gpow_int_val<int3> (n, int3(1, 1, 0)))
//
(* ****** ****** *)

implement
main0 () =
{
//
val N = 10
val () = println! ("fib(", N, ") = ", fib(N))
val N = 20
val () = println! ("fib(", N, ") = ", fib(N))
val N = 30
val () = println! ("fib(", N, ") = ", fib(N))
val N = 40
val () = println! ("fib(", N, ") = ", fib(N))
//
} (* end of [main0] *)

AutoHotkey

Search autohotkey.com: sequence

Iterative

Translation of: C
Loop, 5
  MsgBox % fib(A_Index)
Return

fib(n)
{
  If (n < 2) 
    Return n
  i := last := this := 1
  While (i <= n)
  {
    new := last + this
    last := this
    this := new
    i++
  }
  Return this
}

Recursive and iterative

Source: AutoHotkey forum by Laszlo

/*
Important note: the recursive version would be very slow
without a global or static array. The iterative version
handles also negative arguments properly.
*/

FibR(n) {       ; n-th Fibonacci number (n>=0, recursive with static array Fibo) 
   Static 
   Return n<2 ? n : Fibo%n% ? Fibo%n% : Fibo%n% := FibR(n-1)+FibR(n-2) 
} 

Fib(n) {        ; n-th Fibonacci number (n < 0 OK, iterative) 
   a := 0, b := 1 
   Loop % abs(n)-1 
      c := b, b += a, a := c 
   Return n=0 ? 0 : n>0 || n&1 ? b : -b 
}

AutoIt

Iterative

#AutoIt Version: 3.2.10.0
$n0 = 0
$n1 = 1
$n = 10
MsgBox (0,"Iterative Fibonacci ", it_febo($n0,$n1,$n))

Func it_febo($n_0,$n_1,$N)
   $first = $n_0
   $second = $n_1
   $next = $first + $second
   $febo = 0
   For $i = 1 To $N-3
      $first = $second
      $second = $next
      $next = $first + $second
   Next
   if $n==0 Then
      $febo = 0
   ElseIf $n==1 Then
      $febo = $n_0
   ElseIf $n==2 Then
      $febo = $n_1
   Else
      $febo = $next
   EndIf
   Return $febo
EndFunc

Recursive

#AutoIt Version: 3.2.10.0
$n0 = 0
$n1 = 1
$n = 10
MsgBox (0,"Recursive Fibonacci ", rec_febo($n0,$n1,$n))
Func rec_febo($r_0,$r_1,$R)
   if  $R<3 Then
      if $R==2 Then
	 Return $r_1
      ElseIf $R==1 Then
	 Return $r_0
      ElseIf $R==0 Then
	 Return 0
      EndIf
      Return $R
   Else
      Return rec_febo($r_0,$r_1,$R-1) + rec_febo($r_0,$r_1,$R-2)
   EndIf
EndFunc

AWK

As in many examples, this one-liner contains the function as well as testing with input from stdin, output to stdout.

$ awk 'func fib(n){return(n<2?n:fib(n-1)+fib(n-2))}{print "fib("$1")="fib($1)}'
10
fib(10)=55

Axe

A recursive solution is not practical in Axe because there is no concept of variable scope in Axe.

Iterative solution:

Lbl FIB
r₁→N
0→I
1→J
For(K,1,N)
 I+J→T
 J→I
 T→J
End
J
Return

Babel

In Babel, we can define fib using a stack-based approach that is not recursive:

fib { <- 0 1 { dup <- + -> swap } -> times zap } <

foo x < puts x in foo. In this case, x is the code list between the curly-braces. This is how you define callable code in Babel. The definition works by initializing the stack with 0, 1. On each iteration of the times loop, the function duplicates the top element. In the first iteration, this gives 0, 1, 1. Then it moves down the stack with the <- operator, giving 0, 1 again. It adds, giving 1. then it moves back up the stack, giving 1, 1. Then it swaps. On the next iteration this gives:

1, 1, 1 (dup)  
1, 1, (<-)  
2 (+)  
2, 1 (->)  
1, 2 (swap)  

And so on. To test fib:

{19 iter - fib !} 20 times collect ! lsnum !
Output:
( 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 )

bash

Iterative

$ fib=1;j=1;while((fib<100));do echo $fib;((k=fib+j,fib=j,j=k));done
1
1
2
3
5
8
13
21
34
55
89

Recursive

fib()
{
  if [ $1 -le 0 ]
  then
    echo 0
    return 0
  fi
  if [ $1 -le 2 ]
  then
    echo 1
  else
    a=$(fib $[$1-1])
    b=$(fib $[$1-2])
    echo $(($a+$b))
  fi
}

BASIC

Applesoft BASIC

Same code as Commodore BASIC

Entering a value of N > 183, produces an error message:

?OVERFLOW ERROR IN 220

BASIC256

# Basic-256 ver 1.1.4
# iterative Fibonacci sequence
# Matches sequence A000045 in the OEIS, https://oeis.org/A000045/list

# Return the Nth Fibonacci number

input "N = ",f
limit = 500                        # set upper limit - can be changed, removed
f = int(f)
if f > limit then f = limit        
a = 0 : b = 1 : c = 0 : n = 0      # initial values


while n < f
    print n + chr(9) + c   # chr(9) = tab
    a = b
    b = c
    c = a + b  
    n += 1
        
end while

print " "
print n + chr(9) + c

BBC BASIC

      PRINT FNfibonacci_r(1),  FNfibonacci_i(1)
      PRINT FNfibonacci_r(13), FNfibonacci_i(13)
      PRINT FNfibonacci_r(26), FNfibonacci_i(26)
      END
      
      DEF FNfibonacci_r(N)
      IF N < 2 THEN = N
      = FNfibonacci_r(N-1) + FNfibonacci_r(N-2)
      
      DEF FNfibonacci_i(N)
      LOCAL F, I, P, T
      IF N < 2 THEN = N
      P = 1
      FOR I = 1 TO N
        T = F
        F += P
        P = T
      NEXT
      = F
Output:
         1         1
       233       233
    121393    121393

bootBASIC

Variables in bootBASIC are 2 byte unsigned integers that roll over if there is an overflow. Entering a number greater than 24 will result in an incorrect outcome.

10 print "Enter a ";
20 print "number ";
30 print "greater ";
40 print "than 1";
50 print " and less";
60 print " than 25";
70 input z
80 b=1
90 a=0
100 n=2
110 f=a+b
120 a=b
130 b=f
140 n=n+1
150 if n-z-1 goto 110
160 print "The ";
170 print z ;
180 print "th ";
190 print "Fibonacci ";
200 print "Number is ";
210 print f

Chipmunk Basic

Works with: Chipmunk Basic version 3.6.4
100 cls
110 for i = 0 to 20 : print fibor(i); : next i
120 print
130 for i = 0 to 20 : print fiboi(i); : next i
140 print
150 for i = 0 to 20 : print fiboa(i); : next i
160 end
170 sub fibor(n) : 'Recursive
180   if n < 2 then
190     fibor = n
200   else
210     fibor = fibor(n-1)+fibor(n-2)
220   endif
230 end sub
240 sub fiboi(n) : 'Iterative
250   n1 = 0
260   n2 = 1
270   for k = 1 to abs(n)
280     sum = n1+n2
290     n1 = n2
300     n2 = sum
310   next k
320   if n < 0 then
330     fiboi = n1*((-1)^((-n)+1))
340   else
350     fiboi = n1
360   endif
370 end sub
380 sub fiboa(n) : 'Analytic
390   fiboa = int(0.5+(((sqr 5+1)/2)^n)/sqr 5)
400 end sub
Output:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765

Commodore BASIC

100 PRINT CHR$(147); CHR$(18); "****      FIBONACCI GENERATOR       ****"
110 INPUT "MIN, MAX"; N1, N2
120 IF N1 > N2 THEN T = N1: N1 = N2: N2 = T
130 A = 0: B = 1: S = SGN(N1)
140 FOR I = S TO N1 STEP S
150 : IF S > 0 THEN T = A + B: A = B: B = T
160 : IF S < 0 THEN T = B - A: B = A: A = T
170 NEXT I
180 PRINT
190 PRINT STR$(A); : REM STR$() PREVENTS TRAILING SPACE
200 IF N2 = N1 THEN 250
210 FOR I = N1 + 1 TO N2
220 : T = A + B: A = B: B = T
230 : PRINT ","; STR$(A);
240 NEXT I
250 PRINT
Output:
****      FIBONACCI GENERATOR       ****

MIN, MAX? -6,6

-8, 5,-3, 2,-1, 1, 0, 1, 1, 2, 3, 5, 8

READY.

Craft Basic

let a = 1
let b = 1

print "Fibonacci Sequence"

for i = 0 to 20

	let s = a + b
	let a = b
	let b = s

	print s

next i
Output:
Fibonacci Sequence
2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 

FreeBASIC

Extended sequence coded big integer.

'Fibonacci extended
'Freebasic version 24  Windows
Dim Shared ADDQmod(0 To 19) As Ubyte
Dim Shared ADDbool(0 To 19) As Ubyte

For z As Integer=0 To 19
    ADDQmod(z)=(z Mod 10+48)
    ADDbool(z)=(-(10<=z))
Next z 

Function plusINT(NUM1 As String,NUM2 As String) As String
    Dim As Byte flag
    #macro finish()
    three=Ltrim(three,"0")
    If three="" Then Return "0"
    If flag=1 Then Swap NUM2,NUM1
    Return three
    Exit Function
    #endmacro
    var lenf=Len(NUM1)
    var lens=Len(NUM2)
    If lens>lenf Then 
        Swap NUM2,NUM1
        Swap lens,lenf
        flag=1
    End If
    
    var diff=lenf-lens-Sgn(lenf-lens)
    var three="0"+NUM1
    var two=String(lenf-lens,"0")+NUM2
    Dim As Integer n2
    Dim As Ubyte addup,addcarry
    
    addcarry=0
    
    For n2=lenf-1 To diff Step -1 
        addup=two[n2]+NUM1[n2]-96
        three[n2+1]=addQmod(addup+addcarry)
        addcarry=addbool(addup+addcarry)
    Next n2 
    If addcarry=0 Then 
        finish()
    End If
    If n2=-1 Then 
        three[0]=addcarry+48
        finish()
    End If
    
    For n2=n2 To 0 Step -1 
        addup=two[n2]+NUM1[n2]-96
        three[n2+1]=addQmod(addup+addcarry)
        addcarry=addbool(addup+addcarry)
    Next n2
    three[0]=addcarry+48
    finish()
End Function

Function  fibonacci(n As Integer) As String
    Dim As String sl,l,term
    sl="0": l="1"
    If n=1 Then Return "0"
    If n=2 Then Return "1"
    n=n-2
    For x As Integer= 1 To n
        term=plusINT(l,sl)
        sl=l
        l=term
    Next x
    Function =term
End Function

'==============  EXAMPLE ===============
print "THE SEQUENCE TO 10:"
print
For n As Integer=1 To 10
    Print "term";n;": "; fibonacci(n)
Next n
print
print "Selected Fibonacci number"
print "Fibonacci 500"
print
print fibonacci(500)
Sleep
Output:
THE SEQUENCE TO 10:

term 1: 0
term 2: 1
term 3: 1
term 4: 2
term 5: 3
term 6: 5
term 7: 8
term 8: 13
term 9: 21
term 10: 34

Selected Fibonacci number
Fibonacci 500

86168291600238450732788312165664788095941068326060883324529903470149056115823592
713458328176574447204501

FTCBASIC

define a = 1, b = 1, s = 0, i = 0

cls

print "Fibonacci Sequence"

do

	let s = a + b
	let a = b
	let b = s
	+1 i

	print s

loop i < 20

pause
end


GFA Basic

'
' Compute nth Fibonacci number
'
' open a window for display
OPENW 1
CLEARW 1
' Display some fibonacci numbers
' Fib(46) is the largest number GFA Basic can reach
' (long integers are 4 bytes)
FOR i%=0 TO 46
  PRINT "fib(";i%;")=";@fib(i%)
NEXT i%
' wait for a key press and tidy up
~INP(2)
CLOSEW 1
'
' Function to compute nth fibonacci number
' n must be in range 0 to 46, inclusive
'
FUNCTION fib(n%)
  LOCAL n0%,n1%,nn%,i%
  n0%=0
  n1%=1
  SELECT n%
  CASE 0
    RETURN n0%
  CASE 1
    RETURN n1%
  DEFAULT
    FOR i%=2 TO n%
      nn%=n0%+n1%
      n0%=n1%
      n1%=nn%
    NEXT i%
    RETURN nn%
  ENDSELECT
ENDFUNC

GW-BASIC

Works with: BASICA

Iterative

10 ' SAVE"FIBONA", A
20 ' Secuencia de Fibonacci
30 ' Var
40 DEFDBL D
50 IMAXFIBO% = 76
60 DNUM1 = 1: DNUM2 = DNUM1
70 CLS
80 PRINT "Este programa calcula la serie de Fibonacci."
90 PRINT DNUM1; DNUM2;
100 FOR I% = 1 TO IMAXFIBO%
110   DNUM3 = DNUM1 + DNUM2
120   PRINT DNUM3;
130   DNUM1 = DNUM2: DNUM2 = DNUM3
140 NEXT I%
150 PRINT
160 PRINT "Fin de la ejecución del programa."
170 END
Output:
Este programa calcula la serie de Fibonacci.
 1  1  2  3  5  8  13  21  34  55  89  144  233  377  610  987  1597  2584
 4181  6765  10946  17711  28657  46368  75025  121393  196418  317811  514229
 832040  1346269  2178309  3524578  5702887  9227465  14930352  24157817
 39088169  63245986  102334155  165580141  267914296  433494437  701408733
 1134903170  1836311903  2971215073  4807526976  7778742049  12586269025
 20365011074  32951280099  53316291173  86267571272  139583862445  225851433717
 365435296162  591286729879  956722026041  1548008755920  2504730781961
 4052739537881  6557470319842  10610209857723  17167680177565  27777890035288
 44945570212853  72723460248141  117669030460994  190392490709135
 308061521170129  498454011879264  806515533049393  1304969544928657
 2111485077978050  3416454622906707  5527939700884757  8944394323791464
Fin de la ejecución del programa.
Ok

Binet formula

10 ' SAVE"FIBINF", A
20 ' Secuencia de Fibonacci mediante la fórmula de Binet
30 ' Var
40 DEFDBL D
50 IMAXFIBO% = 77
60 DSQR5 = SQR(5)
70 DPIV1 = (1 + DSQR5) / 2
80 DPIV2 = (1 - DSQR5) / 2
90 DNUM1 = DPIV1: DNUM2 = DPIV2
100 CLS
110 PRINT "Este programa calcula la serie de Fibonacci."
120 FOR I% = 1 TO IMAXFIBO%
130   DNUM1 = DNUM1 * DPIV1
140   DNUM2 = DNUM2 * DPIV2
150   PRINT FIX(((DNUM1 - DNUM2) / DSQR5)+.5);
160 NEXT I%
170 PRINT
180 PRINT "Fin de la ejecución del programa."
190 END
Output:
Este programa calcula la serie de Fibonacci.
 1  2  3  5  8  13  21  34  55  89  144  233  377  610  987  1597  2584  4181
 6765  10946  17711  28657  46368  75025  121393  196418  317811  514229
 832040  1346269  2178310  3524579  5702889  9227468  14930357  24157826
 39088183  63246010  102334195  165580207  267914406  433494620  701409036
 1134903671  1836312733  2971216446  4807529247  7778745802  12586275225
 20365021312  32951296999  53316319058  86267617266  139583938281  225851558714
 365435502118  591287069122  956722584654  1548009675479  2504732295250
 4052742027550  6557474414738  10610216591046  17167691246479  27777908226979
 44945600103607  72723509350188  117669111103547  190392623123089
 308061738545741  498454368657289  806516118510594  1304970505463907
 2111486653578091  3416457206941612  5527943938022908  8944401270367342
Fin de la ejecución del programa.
Ok 

Integer BASIC

Only works with quite small values of .

 10 INPUT N
 20 A=0
 30 B=1
 40 FOR I=2 TO N
 50 C=B
 60 B=A+B
 70 A=C
 80 NEXT I
 90 PRINT B
100 END

IS-BASIC

100 PROGRAM "Fibonac.bas"
110 FOR I=0 TO 20
120   PRINT "F";I,FIB(I)
130 NEXT
140 DEF FIB(N)
150   NUMERIC I
160   LET A=0:LET B=1
170   FOR I=1 TO N
180     LET T=A+B:LET A=B:LET B=T
190   NEXT
200   LET FIB=A
210 END DEF

Liberty BASIC

Iterative/Recursive

Works with: Just BASIC
for i = 0 to 15
    print fiboR(i),fiboI(i)
next i
 
function fiboR(n)
    if n <= 1 then
        fiboR = n
    else
        fiboR = fiboR(n-1) + fiboR(n-2)
    end if
end function
 
function fiboI(n)
    a = 0
    b = 1
    for i = 1 to n
        temp = a + b
        a = b
        b = temp
    next i
    fiboI = a
end function
Output:
0             0
1             1
1             1
2             2
3             3
5             5
8             8
13            13
21            21
34            34
55            55
89            89
144           144
233           233
377           377
610           610

Iterative/Negative

Works with: Just BASIC
print "Rosetta Code - Fibonacci sequence": print
print "  n             Fn"
for x=-12 to 12 '68 max
    print using("### ", x); using("##############", FibonacciTerm(x))
next x
print
[start]
input "Enter a term#: "; n$
n$=lower$(trim$(n$))
if n$="" then print "Program complete.": end
print FibonacciTerm(val(n$))
goto [start]

function FibonacciTerm(n)
    n=int(n)
    FTa=0: FTb=1: FTc=-1
    select case
        case n=0  : FibonacciTerm=0  : exit function
        case n=1  : FibonacciTerm=1  : exit function
        case n=-1 : FibonacciTerm=-1 : exit function
        case n>1
            for x=2 to n
                FibonacciTerm=FTa+FTb
                FTa=FTb: FTb=FibonacciTerm
            next x
            exit function
        case n<-1
            for x=-2 to n step -1
                FibonacciTerm=FTa+FTc
                FTa=FTc: FTc=FibonacciTerm
            next x
            exit function
    end select
end function
Output:
Rosetta Code - Fibonacci sequence

  n             Fn
-12           -144
-11            -89
-10            -55
 -9            -34
 -8            -21
 -7            -13
 -6             -8
 -5             -5
 -4             -3
 -3             -2
 -2             -1
 -1             -1
  0              0
  1              1
  2              1
  3              2
  4              3
  5              5
  6              8
  7             13
  8             21
  9             34
 10             55
 11             89
 12            144

Enter a term#: 12
144
Enter a term#:
Program complete.

Microsoft Small Basic

Iterative

' Fibonacci sequence - 31/07/2018
  n = 139
  f1 = 0
  f2 = 1
  TextWindow.WriteLine("fibo(0)="+f1)
  TextWindow.WriteLine("fibo(1)="+f2)
  For i = 2 To n
    f3 = f1 + f2
    TextWindow.WriteLine("fibo("+i+")="+f3)
    f1 = f2
    f2 = f3
  EndFor
Output:
fibo(139)=50095301248058391139327916261

Binet's Formula

' Fibonacci sequence - Binet's Formula - 31/07/2018
  n = 69
  sq5=Math.SquareRoot(5)
  phi1=(1+sq5)/2
  phi2=(1-sq5)/2
  phi1n=phi1
  phi2n=phi2
  For i = 2 To n
    phi1n=phi1n*phi1
    phi2n=phi2n*phi2
    TextWindow.Write(Math.Floor((phi1n-phi2n)/sq5)+" ")
  EndFor
Output:
1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 12586269025 20365011074 32951280099 53316291173 86267571272 139583862445 225851433717 365435296162 591286729879 956722026041 1548008755920 2504730781961 4052739537881 6557470319842 10610209857723 17167680177565 27777890035288 44945570212853 72723460248141 117669030460994 

Minimal BASIC

Works with: QBasic
Works with: BASICA
Works with: Chipmunk Basic
Works with: GW-BASIC
Works with: IS-BASIC
Works with: MSX Basic
110 REM THE ARRAY F HOLDS THE FIBONACCI NUMBERS
120 DIM F(22)
130 LET F(0) = 0
140 LET F(1) = 1
150 LET N = 1
160 REM COMPUTE THE NEXT FIBBONACCI NUMBER
170 LET F(N+1) = F(N)+F(N-1)
180 LET N = N+1
190 PRINT F(N-2);
200 REM STOP AFTER PRINTING  20 NUMBERS
210 IF N < 22 THEN 170
220 END

MSX Basic

Works with: QBasic
Works with: Chipmunk Basic
Works with: GW-BASIC
100 CLS
110 FOR N = 0 TO 15: GOSUB 130: PRINT FIBOI; : NEXT N
120 END
130 REM Iterative Fibonacci sequence
140 N1 = 0
150 N2 = 1
160 FOR K = 1 TO ABS(N)
170   SUM = N1 + N2
180   N1 = N2
190   N2 = SUM
200 NEXT K
210 IF N < 0 THEN FIBOI = N1 * ((-1) ^ ((-N) + 1)) ELSE FIBOI = N1
220 RETURN

Palo Alto Tiny BASIC

10 REM FIBONACCI SEQUENCE
20 INPUT "ENTER N FOR FIB(N)"N
30 LET A=0,B=1
40 FOR I=2 TO N
50 LET T=B,B=A+B,A=T
60 NEXT I
70 PRINT B
80 STOP
Output:

2 runs.

ENTER N FOR FIB(N):9
     34
ENTER N FOR FIB(N):13
    233

PowerBASIC

Translation of: BASIC

There seems to be a limitation (dare I say, bug?) in PowerBASIC regarding how large numbers are stored. 10E17 and larger get rounded to the nearest 10. For F(n), where ABS(n) > 87, is affected like this:

      actual:             displayed:
F(88) 1100087778366101931 1100087778366101930
F(89) 1779979416004714189 1779979416004714190
F(90) 2880067194370816120 2880067194370816120
F(91) 4660046610375530309 4660046610375530310
F(92) 7540113804746346429 7540113804746346430
FUNCTION fibonacci (n AS LONG) AS QUAD
    DIM u AS LONG, a AS LONG, L0 AS LONG, outP AS QUAD
    STATIC fibNum() AS QUAD

    u = UBOUND(fibNum)
    a = ABS(n)

    IF u < 1 THEN
        REDIM fibNum(1)
        fibNum(1) = 1
        u = 1
    END IF

    SELECT CASE a
        CASE 0 TO 92
            IF a > u THEN
                REDIM PRESERVE fibNum(a)
                FOR L0 = u + 1 TO a
                    fibNum(L0) = fibNum(L0 - 1) + fibNum(L0 - 2)
                    IF 88 = L0 THEN fibNum(88) = fibNum(88) + 1
                NEXT
            END IF
            IF n < 0 THEN
                fibonacci = fibNum(a) * ((-1)^(a+1))
            ELSE
                fibonacci = fibNum(a)
            END IF
        CASE ELSE
            'Even without the above-mentioned bug, we're still limited to
            'F(+/-92), due to data type limits. (F(93) = &hA94F AD42 221F 2702)
            ERROR 6
    END SELECT
END FUNCTION

FUNCTION PBMAIN () AS LONG
    DIM n AS LONG
    #IF NOT %DEF(%PB_CC32)
        OPEN "out.txt" FOR OUTPUT AS 1
    #ENDIF
    FOR n = -92 TO 92
        #IF %DEF(%PB_CC32)
            PRINT STR$(n); ": "; FORMAT$(fibonacci(n), "#")
        #ELSE
            PRINT #1, STR$(n) & ": " & FORMAT$(fibonacci(n), "#")
        #ENDIF
    NEXT
    CLOSE
END FUNCTION

PureBasic

Macro based calculation

Macro Fibonacci (n)
	Int((Pow(((1+Sqr(5))/2),n)-Pow(((1-Sqr(5))/2),n))/Sqr(5))
EndMacro

Recursive

Procedure FibonacciReq(n)
  If n<2
    ProcedureReturn n
  Else
    ProcedureReturn FibonacciReq(n-1)+FibonacciReq(n-2)
  EndIf
EndProcedure

Recursive & optimized with a static hash table

This will be much faster on larger n's, this as it uses a table to store known parts instead of recalculating them. On my machine the speedup compares to above code is

Fib(n) Speedup
20           2
25          23
30         217
40       25847
46     1156741
Procedure Fibonacci(n)
  Static NewMap Fib.i()
  Protected FirstRecursion
  
  If MapSize(Fib())= 0        ; Init the hash table the first run
    Fib("0")=0: Fib("1")=1
    FirstRecursion = #True
  EndIf
 
  If n >= 2
    Protected.s s=Str(n)
    If Not FindMapElement(Fib(),s)  ; Calculate only needed parts
      Fib(s)= Fibonacci(n-1)+Fibonacci(n-2)
    EndIf
    n = Fib(s)  
  EndIf
  If FirstRecursion ; Free the memory when finalizing the first call
    ClearMap(Fib())
  EndIf
  ProcedureReturn n
EndProcedure

Example

Fibonacci(0)= 0
Fibonacci(1)= 1
Fibonacci(2)= 1
Fibonacci(3)= 2
Fibonacci(4)= 3
Fibonacci(5)= 5

FibonacciReq(0)= 0
FibonacciReq(1)= 1
FibonacciReq(2)= 1
FibonacciReq(3)= 2
FibonacciReq(4)= 3
FibonacciReq(5)= 5

QB64

CBTJD: 2020/03/13

_DEFINE F AS _UNSIGNED _INTEGER64
CLS
PRINT
PRINT "Enter 40 to more easily see the difference in calculation speeds."
PRINT
INPUT "Enter n for Fibonacci(n): ", n
PRINT
PRINT " Analytic Method (Fastest): F("; LTRIM$(STR$(n)); ") ="; fA(n)
PRINT "Iterative Method    (Fast): F("; LTRIM$(STR$(n)); ") ="; fI(n)
PRINT "Recursive Method    (Slow): F("; LTRIM$(STR$(n)); ") ="; fR(n)
END

' === Analytic Fibonacci Function (Fastest)
FUNCTION fA (n)
  fA = INT(0.5 + (((SQR(5) + 1) / 2) ^ n) / SQR(5))
END FUNCTION

' === Iterative Fibonacci Function (Fast)
FUNCTION fI (n)
  FOR i = 1 TO n
    IF i < 3 THEN a = 1: b = 1
    t = fI + b: fI = b: b = t
  NEXT
END FUNCTION

' === Recursive Fibonacci function (Slow)
FUNCTION fR (n)
  IF n <= 1 THEN
    fR = n
  ELSE
    fR = fR(n - 1) + fR(n - 2)
  END IF
END FUNCTION

Fibonacci from Russia

DIM F(80) AS DOUBLE 'FibRus.bas DANILIN
F(1) = 0: F(2) = 1
'OPEN "FibRus.txt" FOR OUTPUT AS #1
FOR i = 3 TO 80
    F(i) = F(i-1)+F(i-2)
NEXT i

FOR i = 1 TO 80
    f$ = STR$(F(i)): LF = 22 - LEN(f$)
    n$ = ""
    FOR j = 1 TO LF: n$ = " " + n$: NEXT
    f$ = n$ + f$
    PRINT i, f$: ' PRINT #1, i, f$
NEXT i
Output:
1                                 0
2                                 1
3                                 1
4                                 2
5                                 3
6                                 5
7                                 8
8                                13
9                                21
...
24                            28657
25                            46368
26                            75025
...
36                          9227465
37                         14930352
38                         24157817
...
48                       2971215073
49                       4807526976
50                       7778742049
...
60                     956722026041
61                    1548008755920
62                    2504730781961
...
76                 2111485077978050
77                 3416454622906707
78                 5527939700884757
79                 8944394323791464
80            1.447233402467622D+16

QBasic

Works with: QBasic
Works with: FreeBASIC

Iterative

FUNCTION itFib (n)
    n1 = 0
    n2 = 1
    FOR k = 1 TO ABS(n)
        sum = n1 + n2
        n1 = n2
        n2 = sum
    NEXT k
    IF n < 0 THEN
        itFib = n1 * ((-1) ^ ((-n) + 1))
    ELSE
        itFib = n1
    END IF
END FUNCTION

Next version calculates each value once, as needed, and stores the results in an array for later retreival (due to the use of REDIM PRESERVE, it requires QuickBASIC 4.5 or newer):

DECLARE FUNCTION fibonacci& (n AS INTEGER)

REDIM SHARED fibNum(1) AS LONG

fibNum(1) = 1

'*****sample inputs*****
PRINT fibonacci(0)      'no calculation needed
PRINT fibonacci(13)     'figure F(2)..F(13)
PRINT fibonacci(-42)    'figure F(14)..F(42)
PRINT fibonacci(47)     'error: too big
'*****sample inputs*****

FUNCTION fibonacci& (n AS INTEGER)
    DIM a AS INTEGER
    a = ABS(n)
    SELECT CASE a
        CASE 0 TO 46
            SHARED fibNum() AS LONG
            DIM u AS INTEGER, L0 AS INTEGER
            u = UBOUND(fibNum)
            IF a > u THEN
                REDIM PRESERVE fibNum(a) AS LONG
                FOR L0 = u + 1 TO a
                    fibNum(L0) = fibNum(L0 - 1) + fibNum(L0 - 2)
                NEXT
            END IF
            IF n < 0 THEN
                fibonacci = fibNum(a) * ((-1) ^ (a + 1))
            ELSE
                fibonacci = fibNum(n)
            END IF
        CASE ELSE
            'limited to signed 32-bit int (LONG)
            'F(47)=&hB11924E1
            ERROR 6 'overflow
    END SELECT
END FUNCTION
Output:

(unhandled error in final input prevents output)

 0
 233
-267914296

Recursive

This example can't handle n < 0.

FUNCTION recFib (n)
    IF (n < 2) THEN
	recFib = n
    ELSE
	recFib = recFib(n - 1) + recFib(n - 2)
    END IF
END FUNCTION

Array (Table) Lookup

This uses a pre-generated list, requiring much less run-time processor usage. (Since the sequence never changes, this is probably the best way to do this in "the real world". The same applies to other sequences like prime numbers, and numbers like pi and e.)

DATA -1836311903,1134903170,-701408733,433494437,-267914296,165580141,-102334155
DATA 63245986,-39088169,24157817,-14930352,9227465,-5702887,3524578,-2178309
DATA 1346269,-832040,514229,-317811,196418,-121393,75025,-46368,28657,-17711
DATA 10946,-6765,4181,-2584,1597,-987,610,-377,233,-144,89,-55,34,-21,13,-8,5,-3
DATA 2,-1,1,0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765
DATA 10946,17711,28657,46368,75025,121393,196418,317811,514229,832040,1346269
DATA 2178309,3524578,5702887,9227465,14930352,24157817,39088169,63245986
DATA 102334155,165580141,267914296,433494437,701408733,1134903170,1836311903

DIM fibNum(-46 TO 46) AS LONG

FOR n = -46 TO 46
    READ fibNum(n)
NEXT

'*****sample inputs*****
FOR n = -46 TO 46
    PRINT fibNum(n),
NEXT
PRINT
'*****sample inputs*****

Quite BASIC

100 CLS
110 rem The array F holds the Fibonacci numbers
120 ARRAY f : rem DIM f(22) para Quite BASIC and MSX-BASIC
130 LET f(0) = 0
140 LET f(1) = 1
150 LET n = 1
160 rem Compute the NEXT Fibbonacci number
170 LET f(n+1) = f(n)+f(n-1)
180 LET n = n+1
190 PRINT f(n-2);" ";
200 rem STOP after printing  20 numbers
210 IF n < 22 THEN GOTO 170

Run BASIC

for i = 0 to 10
 print i;" ";fibR(i);" ";fibI(i)
next i
end
 
 function fibR(n)
 if n < 2 then fibR = n else fibR = fibR(n-1) + fibR(n-2)
 end function
 
 function fibI(n)
   b = 1
   for i = 1 to n
       t = a + b
       a = b
       b = t
   next i
fibI = a
end function

S-BASIC

Note that the 23rd Fibonacci number (=28657) is the largest that can be generated without overflowing S-BASIC's integer data type.

rem - iterative function to calculate nth fibonacci number
function fibonacci(n = integer) = integer
var f, i, p1, p2 = integer
p1 = 0    
p2 = 1
if n = 0 then
   f = 0
else
   for i = 1 to n
      f = p1 + p2
      p2 = p1
      p1 = f
   next i
end = f

rem - exercise the function
var i = integer
for i = 0 to 10
   print fibonacci(i);
next i

end
Output:
 0 1 1 2 3 5 8 13 21 34 55

Sinclair ZX81 BASIC

Analytic

 10 INPUT N
 20 PRINT INT (0.5+(((SQR 5+1)/2)**N)/SQR 5)

Iterative

 10 INPUT N
 20 LET A=0
 30 LET B=1
 40 FOR I=2 TO N
 50 LET C=B
 60 LET B=A+B
 70 LET A=C
 80 NEXT I
 90 PRINT B

Tail recursive

 10 INPUT N
 20 LET A=0
 30 LET B=1
 40 GOSUB 70
 50 PRINT B
 60 STOP
 70 IF N=1 THEN RETURN
 80 LET C=B
 90 LET B=A+B
100 LET A=C
110 LET N=N-1
120 GOSUB 70
130 RETURN

smart BASIC

The Iterative method is slow (relatively) and the Recursive method doubly so since it references the recursion function twice.

The N-th Term (fibN) function is much faster as it utilizes Binet's Formula.

  • fibR: Fibonacci Recursive
  • fibI: Fibonacci Iterative
  • fibN: Fibonacci N-th Term
FOR i = 0 TO 15
    PRINT fibR(i),fibI(i),fibN(i)
NEXT i

/* Recursive Method */
DEF fibR(n)
    IF n <= 1 THEN
        fibR = n
    ELSE
        fibR = fibR(n-1) + fibR(n-2)
    ENDIF
END DEF

/* Iterative Method */
DEF fibI(n)
    a = 0
    b = 1
    FOR i = 1 TO n
        temp = a + b
        a = b
        b = temp
    NEXT i
    fibI = a
END DEF

/* N-th Term Method */
DEF fibN(n)
    uphi = .5 + SQR(5)/2
    lphi = .5 - SQR(5)/2
    fibN = (uphi^n-lphi^n)/SQR(5)
END DEF

Softbridge BASIC

Iterative

Function Fibonacci(n)
   x = 0
   y = 1
   i = 0
   n = ABS(n)
   If n < 2 Then
   Fibonacci = n
   Else
   Do Until (i = n)
      sum = x+y
      x=y
      y=sum
      i=i+1
   Loop
   Fibonacci = x
   End If

End Function

TI-83 BASIC

Sequence table

[Y=]
nMin=0
u(n)=u(n-1)+u(n-2)
u(nMin)={1,0}
[TABLE]
n	u(n)
-------	-------
0	0
1	1
2	1
3	2
4	3
5	5
6	8
7	13
8	21
9	34
10	55
11	89
12	144

Iterative

{0,1
While 1
Disp Ans(1
{Ans(2),sum(Ans
End

Binet's formula

Prompt N
.5(1+√(5    //golden ratio
(Ans^N–(-Ans)^-N)/√(5

TI-89 BASIC

Recursive

Optimized implementation (too slow to be usable for n higher than about 12).

fib(n)
when(n<2, n, fib(n-1) + fib(n-2))

Iterative

Unoptimized implementation (I think the for loop can be eliminated, but I'm not sure).

fib(n)
Func
Local a,b,c,i
0→a
1→b
For i,1,n
  a→c
  b→a
  c+b→b
EndFor
a
EndFunc

Tiny BASIC

Works with: TinyBasic
10 LET A = 0
20 LET B = 1
30 PRINT "Which F_n do you want?"
40 INPUT N
50 IF N = 0 THEN GOTO 140
60 IF N = 1 THEN GOTO 120
70 LET C = B + A
80 LET A = B
90 LET B = C
100 LET N = N - 1
110 GOTO 60
120 PRINT B
130 END
140 PRINT 0
150 END

True BASIC

FUNCTION fibonacci (n)
    LET n1 = 0
    LET n2 = 1
    FOR k = 1 TO ABS(n)
        LET sum = n1 + n2
        LET n1 = n2
        LET n2 = sum
    NEXT k
    IF n < 0 THEN
       LET fibonacci = n1 * ((-1) ^ ((-n) + 1))
    ELSE
       LET fibonacci = n1
    END IF
END FUNCTION

PRINT fibonacci(0)      ! 0
PRINT fibonacci(13)     ! 233
PRINT fibonacci(-42)    !-267914296
PRINT fibonacci(47)     ! 2971215073
END

VBA

Like Visual Basic .NET, but with keyword "Public" and type Variant (subtype Currency) instead of Decimal:

Public Function Fib(ByVal n As Integer) As Variant
    Dim fib0 As Variant, fib1 As Variant, sum As Variant
    Dim i As Integer
    fib0 = 0
    fib1 = 1
    For i = 1 To n
        sum = fib0 + fib1
        fib0 = fib1
        fib1 = sum
    Next i
    Fib = fib0
End Function

With Currency type, maximum value is fibo(73).

The (slow) recursive version:

Public Function RFib(Term As Integer) As Long
  If Term < 2 Then RFib = Term Else RFib = RFib(Term - 1) + RFib(Term - 2)
End Function

With Long type, maximum value is fibo(46).

VBScript

Non-recursive, object oriented, generator

Defines a generator class, with a default Get property. Uses Currency for larger-than-Long values. Tests for overflow and switches to Double. Overflow information also available from class.

Class Definition:
class generator
	dim t1
	dim t2
	dim tn
	dim cur_overflow
	
	Private Sub Class_Initialize
		cur_overflow = false
		t1 = ccur(0)
		t2 = ccur(1)
		tn = ccur(t1 + t2)
	end sub
	
	public default property get generated
		on error resume next

		generated = ccur(tn)
		if err.number <> 0 then 
			generated = cdbl(tn)
			cur_overflow = true
		end if
		t1 = ccur(t2)
		if err.number <> 0 then 
			t1 = cdbl(t2)
			cur_overflow = true
		end if
		t2 = ccur(tn)
		if err.number <> 0 then 
			t2 = cdbl(tn)
			cur_overflow = true
		end if
		tn = ccur(t1+ t2)
		if err.number <> 0 then 
			tn = cdbl(t1) + cdbl(t2)
			cur_overflow = true
		end if
		on error goto 0
	end property
	
	public property get overflow
		overflow = cur_overflow
	end property
		
end class
Invocation:
dim fib
set fib = new generator
dim i
for i = 1 to 100
	wscript.stdout.write " " & fib 
	if fib.overflow then
		wscript.echo
		exit for
	end if
next
Output:
 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 12586269025 20365011074 32951280099 53316291173 86267571272 139583862445 225851433717 365435296162 591286729879 956722026041 1548008755920 2504730781961 4052739537881 6557470319842 10610209857723 17167680177565 27777890035288 44945570212853 72723460248141 117669030460994 190392490709135 308061521170129 498454011879264 806515533049393

Visual Basic

Works with: Visual Basic version VB6 Standard

Maximum integer value (7*10^28) can be obtained by using decimal type, but decimal type is only a sub type of the variant type.

Sub fibonacci()
    Const n = 139 
    Dim i As Integer
    Dim f1 As Variant, f2 As Variant, f3 As Variant 'for Decimal
    f1 = CDec(0): f2 = CDec(1) 'for Decimal setting
    Debug.Print "fibo("; 0; ")="; f1
    Debug.Print "fibo("; 1; ")="; f2
    For i = 2 To n
        f3 = f1 + f2
        Debug.Print "fibo("; i; ")="; f3
        f1 = f2
        f2 = f3
    Next i
End Sub 'fibonacci
Output:
fibo( 0 )= 0 
fibo( 1 )= 1 
fibo( 2 )= 1 
...
fibo( 137 )= 19134702400093278081449423917 
fibo( 138 )= 30960598847965113057878492344 
fibo( 139 )= 50095301248058391139327916261 

Visual Basic .NET

Platform: .NET

Iterative

Works with: Visual Basic .NET version 9.0+

With Decimal type, maximum value is fibo(139).

Function Fib(ByVal n As Integer) As Decimal
    Dim fib0, fib1, sum As Decimal
    Dim i As Integer
    fib0 = 0
    fib1 = 1
    For i = 1 To n
        sum = fib0 + fib1
        fib0 = fib1
        fib1 = sum
    Next
    Fib = fib0
End Function

Recursive

Works with: Visual Basic .NET version 9.0+
Function Seq(ByVal Term As Integer)
        If Term < 2 Then Return Term
        Return Seq(Term - 1) + Seq(Term - 2)
End Function

BigInteger

There is no real maximum value of BigInterger class, except the memory to store the number. Within a minute, fibo(2000000) is a number with 417975 digits.

    Function FiboBig(ByVal n As Integer) As BigInteger
        ' Fibonacci sequence with BigInteger
        Dim fibn2, fibn1, fibn As BigInteger
        Dim i As Integer
        fibn = 0
        fibn2 = 0
        fibn1 = 1
        If n = 0 Then
            Return fibn2
        ElseIf n = 1 Then
            Return fibn1
        ElseIf n >= 2 Then
            For i = 2 To n
                fibn = fibn2 + fibn1
                fibn2 = fibn1
                fibn1 = fibn
            Next i
            Return fibn
        End If
        Return 0
    End Function 'FiboBig

    Sub fibotest()
        Dim i As Integer, s As String
        i = 2000000  ' 2 millions
        s = FiboBig(i).ToString
        Console.WriteLine("fibo(" & i & ")=" & s & " - length=" & Len(s))
    End Sub 'fibotest

BigInteger, speedier method

This method doesn't need to iterate the entire list, and is much faster. The 2000000 (two millionth) Fibonacci number can be found in a fraction of a second.
Algorithm from here, see section 3, Finding Fibonacci Numbers Fully.

Imports System
Imports System.Collections.Generic
Imports BI = System.Numerics.BigInteger

Module Module1

    ' A sparse array of values calculated along the way
    Dim sl As SortedList(Of Integer, BI) = New SortedList(Of Integer, BI)()

    ' Square a BigInteger
    Function sqr(ByVal n As BI) As BI
        Return n * n
    End Function

    ' Helper routine for Fsl(). It adds an entry to the sorted list when necessary
    Sub IfNec(n As Integer)
        If Not sl.ContainsKey(n) Then sl.Add(n, Fsl(n))
    End Sub

    ' This routine is semi-recursive, but doesn't need to evaluate every number up to n.
    ' Algorithm from here: http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormula.html#section3
    Function Fsl(ByVal n As Integer) As BI
        If n < 2 Then Return n
        Dim n2 As Integer = n >> 1, pm As Integer = n2 + ((n And 1) << 1) - 1 : IfNec(n2) : IfNec(pm)
        Return If(n2 > pm, (2 * sl(pm) + sl(n2)) * sl(n2), sqr(sl(n2)) + sqr(sl(pm)))
    End Function

    ' Conventional iteration method (not used here)
    Function Fm(ByVal n As BI) As BI
        If n < 2 Then Return n
        Dim cur As BI = 0, pre As BI = 1
        For i As Integer = 0 To n - 1
            Dim sum As BI = cur + pre : pre = cur : cur = sum : Next : Return cur
    End Function

    Sub Main()
        Dim vlen As Integer, num As Integer = 2_000_000, digs As Integer = 35
        Dim sw As System.Diagnostics.Stopwatch = System.Diagnostics.Stopwatch.StartNew()
        Dim v As BI = Fsl(num) : sw.[Stop]()
        Console.Write("{0:n3} ms to calculate the {1:n0}th Fibonacci number, ", sw.Elapsed.TotalMilliseconds, num)
        vlen = CInt(Math.Ceiling(BI.Log10(v))) : Console.WriteLine("number of digits is {0}", vlen)
        If vlen < 10000 Then
            sw.Restart() : Console.WriteLine(v) : sw.[Stop]()
            Console.WriteLine("{0:n3} ms to write it to the console.", sw.Elapsed.TotalMilliseconds)
        Else
            Console.Write("partial: {0}...{1}", v / BI.Pow(10, vlen - digs), v Mod BI.Pow(10, digs))
        End If
    End Sub
End Module
Output:
120.374 ms to calculate the 2,000,000th Fibonacci number, number of digits is 417975
partial: 85312949175076415430516606545038251...91799493108960825129188777803453125

Xojo

Pass n to this function where n is the desired number of iterations. This example uses the UInt64 datatype which is as unsigned 64 bit integer. As such, it overflows after the 93rd iteration.

Function fibo(n As Integer) As UInt64

  Dim noOne As UInt64 = 1
  Dim noTwo As UInt64 = 1	
  Dim sum As UInt64

  For i As Integer = 3 To n
      sum = noOne + noTwo
      noTwo = noOne
      noOne = sum
  Next

  Return noOne
End Function

Yabasic

Iterative

sub fibonacciI (n)
    local n1, n2, k, sum

    n1 = 0
    n2 = 1
    for k = 1 to abs(n)
        sum = n1 + n2
        n1 = n2
        n2 = sum
    next k
    if n < 1 then
       return n1 * ((-1) ^ ((-n) + 1))
    else
       return n1
    end if
end sub

Recursive

Only positive numbers

sub fibonacciR(n)
    if n <= 1 then
        return n
    else
        return fibonacciR(n-1) + fibonacciR(n-2)
    end if
end sub

Analytic

Only positive numbers

sub fibonacciA (n)
    return int(0.5 + (((sqrt(5) + 1) / 2) ^ n) / sqrt(5))
end sub

Binet's formula

Fibonacci sequence using the Binet formula

sub fibonacciB(n)
    local sq5, phi1, phi2, dn1, dn2, k

    sq5 = sqrt(5)
    phi1 = (1 + sq5) / 2
    phi2 = (1 - sq5) / 2
    dn1 = phi1: dn2 = phi2
    for k = 0 to n
        dn1 = dn1 * phi1
        dn2 = dn2 * phi2
        print int(((dn1 - dn2) / sq5) + .5);
    next k
end sub

ZX Spectrum Basic

Iterative

10 REM Only positive numbers
20 LET n=10
30 LET n1=0: LET n2=1
40 FOR k=1 TO n
50 LET sum=n1+n2
60 LET n1=n2
70 LET n2=sum
80 NEXT k
90 PRINT n1

Analytic

10 DEF FN f(x)=INT (0.5+(((SQR 5+1)/2)^x)/SQR 5)

Batch File

Recursive version

::fibo.cmd
@echo off
if "%1" equ "" goto :eof
call :fib %1
echo %errorlevel%
goto :eof

:fib
setlocal enabledelayedexpansion
if %1 geq 2 goto :ge2 
exit /b %1

:ge2
set /a r1 = %1 - 1
set /a r2 = %1 - 2
call :fib !r1!
set r1=%errorlevel%
call :fib !r2!
set r2=%errorlevel%
set /a r0 = r1 + r2
exit /b !r0!
Output:
>for /L %i in (1,5,20) do fibo.cmd %i

>fibo.cmd 1
1

>fibo.cmd 6
8

>fibo.cmd 11
89

>fibo.cmd 16
987

Battlestar

// Fibonacci sequence, recursive version
fun fibb
    loop
        a = funparam[0]
        break (a < 2)

        a--

        // Save "a" while calling fibb
        a -> stack

        // Set the parameter and call fibb
        funparam[0] = a
        call fibb

        // Handle the return value and restore "a"
        b = funparam[0]
        stack -> a

        // Save "b" while calling fibb again
        b -> stack

        a--

        // Set the parameter and call fibb
        funparam[0] = a
        call fibb

        // Handle the return value and restore "b"
        c = funparam[0]
        stack -> b

        // Sum the results
        b += c
        a = b

        funparam[0] = a

        break
    end
end

// vim: set syntax=c ts=4 sw=4 et:

bc

iterative

#! /usr/bin/bc -q

define fib(x) {
    if (x <= 0) return 0;
    if (x == 1) return 1;

    a = 0;
    b = 1;
    for (i = 1; i < x; i++) {
        c = a+b; a = b; b = c;
    }
    return c;
}
fib(1000)
quit

BCPL

get "libhdr"

let fib(n) = n<=1 -> n, valof
$(  let a=0 and b=1
    for i=2 to n
    $(  let c=a
        a := b
        b := a+c
    $)
    resultis b
$)

let start() be
    for i=0 to 10 do
        writef("F_%N*T= %N*N", i, fib(i))
Output:
F_0     = 0
F_1     = 1
F_2     = 1
F_3     = 2
F_4     = 3
F_5     = 5
F_6     = 8
F_7     = 13
F_8     = 21
F_9     = 34
F_10    = 55

beeswax

                        #>'#{;
_`Enter n: `TN`Fib(`{`)=`X~P~K#{;
                         #>~P~L#MM@>+@'q@{;
                                    b~@M<

Example output:

Notice the UInt64 wrap-around at Fib(94)!

julia> beeswax("n-th Fibonacci number.bswx")
Enter n: i0

Fib(0)=0
Program finished!

julia> beeswax("n-th Fibonacci number.bswx")
Enter n: i10
         
Fib(10)=55
Program finished!

julia> beeswax("n-th Fibonacci number.bswx")
Enter n: i92

Fib(92)=7540113804746346429
Program finished!

julia> beeswax("n-th Fibonacci number.bswx")
Enter n: i93
                                                                             
Fib(93)=12200160415121876738                                                 
Program finished!                                                            

julia> beeswax("n-th Fibonacci number.bswx")
Enter n: i94                                                                 
                                                                             
Fib(94)=1293530146158671551                                                  
Program finished!

Befunge

00:.1:.>:"@"8**++\1+:67+`#@_v
       ^ .:\/*8"@"\%*8"@":\ <

BlitzMax

local a:int = 0, b:int = 1, c:int = 1, n:int

n = int(input( "Enter n: "))
if n = 0 then
    print 0
    end
else if n = 1
    print 1
    end
end if

while n>2
    a = b
    b = c
    c = a + b
    n = n - 1
wend
print c

Blue

: fib ( nth:ecx -- result:edi ) 1 0 
: compute ( times:ecx accum:eax scratch:edi -- result:edi ) xadd latest loop ;

: example ( -- ) 11 fib drop ;

BQN

All given functions return the nth element in the sequence.

Recursive

A primitive recursive can be done with predicates:

Fib  {𝕩>1 ? (𝕊 𝕩-1) + 𝕊 𝕩-2; 𝕩}

Or, it can be done with the Choose() modifier:

Fib2  {(𝕩-1) (𝕩>1)𝕩, +𝕊 𝕩-2}

Iterative

An iterative solution can be made with the Repeat() modifier:

{(+`)𝕩 01}

Bracmat

Recursive

fib=.!arg:<2|fib$(!arg+-2)+fib$(!arg+-1)
 fib$30
 832040

Iterative

(fib=
  last i this new
.   !arg:<2
  |   0:?last:?i
    & 1:?this
    &   whl
      ' ( !i+1:<!arg:?i
        & !last+!this:?new
        & !this:?last
        & !new:?this
        )
    & !this
)
 fib$777
 1081213530912648191985419587942084110095342850438593857649766278346130479286685742885693301250359913460718567974798268702550329302771992851392180275594318434818082

Brainf***

Works with: Brainf*** version implementations with unbounded cell size

The first cell contains n (10), the second cell will contain fib(n) (55), and the third cell will contain fib(n-1) (34).

++++++++++
>>+<<[->[->+>+<<]>[-<+>]>[-<+>]<<<]

The following generates n fibonacci numbers and prints them, though not in ascii. It does have a limit due to the cells usually being 1 byte in size.

+++++ +++++	#0 set to n
>> +		Init #2 to 1
<<
[
	-	#Decrement counter in #0
	>>.	Notice: This doesn't print it in ascii
		To look at results you can pipe into a file and look with a hex editor
	
		Copying sequence to save #2 in #4 using #5 as restore space
	>>[-]	Move to #4 and clear
	>[-]	Clear #5
	<<<	#2
	[	Move loop
		- >> + > + <<<	Subtract #2 and add #4 and #5
	]
	>>>
	[	Restore loop
		- <<< + >>>	Subtract from #5 and add to #2
	]

	<<<<	Back to #1
		Non destructive add sequence using #3 as restore value
	[	Loop to add
		- > + > + <<	Subtract #1 and add to value #2 and restore space #3
	]
	>>
	[	Loop to restore #1 from #3
		- << + >>	Subtract from restore space #3 and add in #1
	]
	
	<< [-]	Clear #1
	>>>
	[	Loop to move #4 to #1
		- <<< + >>>	Subtract from #4 and add to #1
	]
	<<<<	Back to #0
]

Brat

Recursive

fibonacci = { x |
        true? x < 2, x, { fibonacci(x - 1) + fibonacci(x - 2) }
}

Tail Recursive

fib_aux = { x, next, result |
        true? x == 0,
                result,
                { fib_aux x - 1, next + result, next }
}

fibonacci = { x |
  fib_aux x, 1, 0
}

Memoization

cache = hash.new

fibonacci = { x |
  true? cache.key?(x)
    { cache[x] }
    {true? x < 2, x, { cache[x] = fibonacci(x - 1) + fibonacci(x - 2) }}
}

Bruijn

:import std/Combinator .
:import std/Math .
:import std/List .

# unary/Church fibonacci (moderately fast but very high space complexity)
fib-unary [0 [[[2 0 [2 (1 0)]]]] k i]

:test (fib-unary (+6u)) ((+8u))

# ternary fibonacci using infinite list iteration (very fast)
fib-list \index fibs
	fibs head <$> (iterate &[[0 : (1 + 0)]] ((+0) : (+1)))

:test (fib-list (+6)) ((+8))

# recursive fib (very slow)
fib-rec y [[0 <? (+1) (+0) (0 <? (+2) (+1) rec)]]
	rec (1 --0) + (1 --(--0))

:test (fib-rec (+6)) ((+8))

Performance using HigherOrder reduction without optimizations:

> :time fib-list (+1000)
0.9 seconds
> :time fib-unary (+50u)
1.7 seconds
> :time fib-rec (+25)
5.1 seconds
> :time fib-list (+50)
0.0006 seconds

Burlesque

{0 1}{^^++[+[-^^-]\/}30.*\[e!vv
0 1{{.+}c!}{1000.<}w!

C

Recursive

long long fibb(long long a, long long b, int n) {
    return (--n>0)?(fibb(b, a+b, n)):(a);
}

Iterative

long long int fibb(int n) {
	int fnow = 0, fnext = 1, tempf;
	while(--n>0){
		tempf = fnow + fnext;
		fnow = fnext;
		fnext = tempf;
		}
		return fnext;	
}

Analytic

#include <tgmath.h>
#define PHI ((1 + sqrt(5))/2)

long long unsigned fib(unsigned n) {
    return floor( (pow(PHI, n) - pow(1 - PHI, n))/sqrt(5) );
}

Generative

Translation of: Python
Works with: gcc version version 4.1.2 20080704 (Red Hat 4.1.2-44)
#include <stdio.h>
typedef enum{false=0, true=!0} bool;
typedef void iterator;

#include <setjmp.h>
/* declare label otherwise it is not visible in sub-scope */
#define LABEL(label) jmp_buf label; if(setjmp(label))goto label;
#define GOTO(label) longjmp(label, true)

/* the following line is the only time I have ever required "auto" */
#define FOR(i, iterator) { auto bool lambda(i); yield_init = (void *)&lambda; iterator; bool lambda(i)
#define DO {
#define     YIELD(x) if(!yield(x))return
#define     BREAK    return false
#define     CONTINUE return true
#define OD CONTINUE; } }

static volatile void *yield_init; /* not thread safe */
#define YIELDS(type) bool (*yield)(type) = yield_init

iterator fibonacci(int stop){
    YIELDS(int);
    int f[] = {0, 1};
    int i;
    for(i=0; i<stop; i++){
        YIELD(f[i%2]);
        f[i%2]=f[0]+f[1];
    }
}

main(){
  printf("fibonacci: ");
  FOR(int i, fibonacci(16)) DO
    printf("%d, ",i);
  OD;
  printf("...\n");
}
Output:
fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, ...

Fast method for a single large value

#include <stdlib.h>
#include <stdio.h>
#include <gmp.h>

typedef struct node node;
struct node {
	int n;
	mpz_t v;
	node *next;
};

#define CSIZE 37
node *cache[CSIZE];

// very primitive linked hash table
node * find_cache(int n)
{
	int idx = n % CSIZE;
	node *p;

	for (p = cache[idx]; p && p->n != n; p = p->next);
	if (p) return p;

	p = malloc(sizeof(node));
	p->next = cache[idx];
	cache[idx] = p;

	if (n < 2) {
		p->n = n;
		mpz_init_set_ui(p->v, 1);
	} else {
		p->n = -1; // -1: value not computed yet
		mpz_init(p->v);
	}
	return p;
}

mpz_t tmp1, tmp2;
mpz_t *fib(int n)
{
	int x;
	node *p = find_cache(n);

	if (p->n < 0) {
		p->n = n;
		x = n / 2;

		mpz_mul(tmp1, *fib(x-1), *fib(n - x - 1));
		mpz_mul(tmp2, *fib(x), *fib(n - x));
		mpz_add(p->v, tmp1, tmp2);
	}
	return &p->v;
}

int main(int argc, char **argv)
{
	int i, n;
	if (argc < 2) return 1;

	mpz_init(tmp1);
	mpz_init(tmp2);

	for (i = 1; i < argc; i++) {
		n = atoi(argv[i]);
		if (n < 0) {
			printf("bad input: %s\n", argv[i]);
			continue;
		}

		// about 75% of time is spent in printing
		gmp_printf("%Zd\n", *fib(n));
	}
	return 0;
}
Output:
% ./a.out 0 1 2 3 4 5
1
1
2
3
5
8
% ./a.out 10000000 | wc -c    # count length of output, including the newline
1919488

C#

Recursive

public static ulong Fib(uint n) {
    return (n < 2)? n : Fib(n - 1) + Fib(n - 2);
}

Tail-Recursive

public static ulong Fib(uint n) {
    return Fib(0, 1, n);
}

private static ulong Fib(ulong a, ulong b, uint n) {
    return (n < 1)? a :(n == 1)?  b : Fib(b, a + b, n - 1);
}

Iterative

public static ulong Fib(uint x) {
    if (x == 0) return 0;

    ulong prev = 0;
    ulong next = 1;
    for (int i = 1; i < x; i++)
    {
        ulong sum = prev + next;
        prev = next;
        next = sum;
    }
    return next;
}

Iterative

using System; using System.Text; // FIBRUS.cs Russia
namespace Fibrus { class Program { static void Main() 
{ long fi1=1; long fi2=1; long fi3=1; int da; int i; int d; 
for (da=1; da<=78; da++) // rextester.com/MNGUV70257
    { d = 20-Convert.ToInt32((Convert.ToString(fi3)).Length);
    for (i=1; i<d; i++) Console.Write(".");
Console.Write(fi3); Console.Write(" "); Console.WriteLine(da);
    fi3 = fi2 + fi1;
    fi1 = fi2;
    fi2 = fi3;
}}}}
Output:
..................1 1
..................2 2
..................3 3
...
...5527939700884757 76
...8944394323791464 77
..14472334024676221 78

Eager-Generative

public static IEnumerable<long> Fibs(uint x) {
    IList<ulong> fibs = new List<ulong>();

    ulong prev = -1;
    ulong next = 1;
    for (int i = 0; i < x; i++)
    {
     long sum = prev + next;
        prev = next;
        next = sum;
        fibs.Add(sum); 
    }
    return fibs;
}

Lazy-Generative

public static IEnumerable<ulong> Fibs(uint x) {
    ulong prev = -1;
    ulong next = 1;
    for (uint i = 0; i < x; i++) {
        ulong sum = prev + next;
        prev = next;
        next = sum;
        yield return sum;
    }
}

Analytic

This returns digits up to the 93rd Fibonacci number, but the digits become inaccurate past the 71st. There is custom rounding applied to the result that allows the function to be accurate at the 71st number instead of topping out at the 70th.

static double r5 = Math.Sqrt(5.0), Phi = (r5 + 1.0) / 2.0;

static ulong fib(uint n) {
    if (n > 71) throw new ArgumentOutOfRangeException("n", n, "Needs to be smaller than 72."); 
    double r = Math.Pow(Phi, n) / r5; 
    return (ulong)(n < 64 ? Math.Round(r) : Math.Floor(r)); }

To get to the 93rd Fibonacci number, one must use the decimal type, rather than the double type, like this:

static decimal Sqrt_dec(decimal x, decimal g) { decimal t, lg;
    do { t = x / g; lg = g; g = (t + g) / 2M; } while (lg != g);
    return g; }

static decimal Pow_dec (decimal bas, uint exp) {
    if (exp == 0) return 1M;
    decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp;
    if ((exp & 1) == 1) tmp *= bas; return tmp; }

static decimal r5 = Sqrt_dec(5.0M, (decimal)Math.Sqrt(5.0)),
               Phi = (r5 + 1.0M) / 2.0M;

static ulong fib(uint n) {
    if (n > 93) throw new ArgumentOutOfRangeException("n", n, "Needs to be smaller than 94."); 
    decimal r = Pow_dec(Phi, n) / r5; 
    return (ulong)(n < 64 ? Math.Round(r) : Math.Floor(r)); }

Note that the Math.Pow() function and the Math.Sqrt() function must be replaced with ones returning the decimal type.

If one allows the fib() function to return the decimal type, one can reach the 138th Fibonacci number. However, the accuracy is lost after the 128th.

static decimal Sqrt_dec(decimal x, decimal g) { decimal t, lg;
    do { t = x / g; lg = g; g = (t + g) / 2M; } while (lg != g);
    return g; }

static decimal Pow_dec (decimal bas, uint exp) {
    if (exp == 0) return 1M;
    decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp;
    if ((exp & 1) == 1) tmp *= bas; return tmp; }

static decimal r5 = Sqrt_dec(5.0M, (decimal)Math.Sqrt(5.0)),
               Phi = (r5 + 1.0M) / 2.0M;

static decimal fib(uint n) {
    if (n > 128) throw new ArgumentOutOfRangeException("n", n, "Needs to be smaller than 129."); 
    decimal r = Pow_dec(Phi, n) / r5; 
    return n < 64 ? Math.Round(r) : Math.Floor(r); }

Matrix

Algorithm is based on

.

Needs System.Windows.Media.Matrix or similar Matrix class. Calculates in .

public static ulong Fib(uint n) {
    var M = new Matrix(1,0,0,1);
    var N = new Matrix(1,1,1,0);
    for (uint i = 1; i < n; i++) M *= N;
    return (ulong)M[0][0];
}

Needs System.Windows.Media.Matrix or similar Matrix class. Calculates in .

private static Matrix M;
private static readonly Matrix N = new Matrix(1,1,1,0);

public static ulong Fib(uint n) {
    M = new Matrix(1,0,0,1);
    MatrixPow(n-1);
    return (ulong)M[0][0];
}

private static void MatrixPow(double n){
    if (n > 1) {
        MatrixPow(n/2);
        M *= M;
    }
    if (n % 2 == 0) M *= N;
}

Array (Table) Lookup

private static int[] fibs = new int[]{ -1836311903, 1134903170, 
  -701408733, 433494437, -267914296, 165580141, -102334155, 
  63245986, -39088169, 24157817, -14930352, 9227465, -5702887, 
  3524578, -2178309, 1346269, -832040, 514229, -317811, 196418, 
  -121393, 75025, -46368, 28657, -17711, 10946, -6765, 4181, 
  -2584, 1597, -987, 610, -377, 233, -144, 89, -55, 34, -21, 13, 
  -8, 5, -3, 2, -1, 1, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 
  144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711,
  28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040,
  1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817,
  39088169, 63245986, 102334155, 165580141, 267914296, 433494437,
  701408733, 1134903170, 1836311903};

public static int Fib(int n) {
    if(n < -46 || n > 46) throw new ArgumentOutOfRangeException("n", n, "Has to be between -46 and 47.")
    return fibs[n+46];
}

Arbitrary Precision

This large step recurrence routine can calculate the two millionth Fibonacci number in under 1 / 5 second at tio.run. This routine can generate the fifty millionth Fibonacci number in under 30 seconds at tio.run. The unused conventional iterative method times out at two million on tio.run, you can only go to around 1,290,000 or so to keep the calculation time (plus string conversion time) under the 60 second timeout limit there. When using this large step recurrence method, it takes around 5 seconds to convert the two millionth Fibonacci number (417975 digits) into a string (so that one may count those digits).

using System;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
 
class Program
{
    // A sparse array of values calculated along the way
    static SortedList<int, BI> sl = new SortedList<int, BI>();
 
    // This routine is semi-recursive, but doesn't need to evaluate every number up to n.
    // Algorithm from here: http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormula.html#section3
    static BI Fsl(int n)
    {
        if (n < 2) return n;
        int n2 = n >> 1, pm = n2 + ((n & 1) << 1) - 1; IfNec(n2); IfNec(pm);
        return n2 > pm ? (2 * sl[pm] + sl[n2]) * sl[n2] : sqr(sl[n2]) + sqr(sl[pm]);
        // Helper routine for Fsl(). It adds an entry to the sorted list when necessary
        void IfNec(int x) { if (!sl.ContainsKey(x)) sl.Add(x, Fsl(x)); }
        // Helper function to square a BigInteger
        BI sqr(BI x) { return x * x; }
    }
 
    // Conventional iteration method (not used here)
    public static BI Fm(BI n)
    {
        if (n < 2) return n; BI cur = 0, pre = 1;
        for (int i = 0; i <= n - 1; i++) { BI sum = cur + pre; pre = cur; cur = sum; }
        return cur;
    }
 
    public static void Main()
    {
        int num = 2_000_000, digs = 35, vlen;
        var sw = System.Diagnostics.Stopwatch.StartNew(); var v = Fsl(num); sw.Stop();
        Console.Write("{0:n3} ms to calculate the {1:n0}th Fibonacci number, ",
          sw.Elapsed.TotalMilliseconds, num);
        Console.WriteLine("number of digits is {0}", vlen = (int)Math.Ceiling(BI.Log10(v)));
        if (vlen < 10000) {
            sw.Restart(); Console.WriteLine(v); sw.Stop();
            Console.WriteLine("{0:n3} ms to write it to the console.", sw.Elapsed.TotalMilliseconds);
        } else
            Console.Write("partial: {0}...{1}", v / BI.Pow(10, vlen - digs), v % BI.Pow(10, digs));
    }
}
Output:
137.209 ms to calculate the 2,000,000th Fibonacci number, number of digits is 417975
partial: 85312949175076415430516606545038251...91799493108960825129188777803453125

Shift PowerMod

Illustrated here is an algorithm to compute a Fibonacci number directly, without needing to calculate any of the Fibonacci numbers less than the desired result. It uses shifting and the power mod function (BigInteger.ModPow() in C#). It calculates more quickly than the large step recurrence routine (illustrated above) for smaller Fibonacci numbers (less than 2800 digits or so, around Fibonacci(13000)), but gets slower for larger ones, as the intermediate BigIntegers created are very large, much larger than the Fibonacci result.

Also included is a routine that returns an array of Fibonacci numbers (fibTab()). It reuses the intermediate large shifted BigIntegers on suceeding iterations, therfore it is a little more efficient than calling the oneshot (oneFib()) routine repeatedly from a loop.

using System;
using BI = System.Numerics.BigInteger;

class Program {
  
  // returns the nth Fibonacci number without calculating 0..n-1
  static BI oneFib(int n) {
    BI z = (BI)1 << ++n;
    return BI.ModPow(z, n, (z << n) - z - 1) % z;
  }

  // returns an array of Fibonacci numbers from the 0th to the nth
  static BI[] fibTab(int n) {
    var res = new BI[++n];
    BI z = (BI)1 << 1, zz = z << 1;
    for (int i = 0; i < n; ) {
      res[i] = BI.ModPow(z, ++i, zz - z - 1) % z;
      z <<= 1; zz <<= 2;
    }
    return res;
  }
  
  static void Main(string[] args) {
    int n = 20;
    Console.WriteLine("Fibonacci numbers 0..{0}: {1}", n, string.Join(" ",fibTab(n)));
    n = 1000;
    Console.WriteLine("Fibonacci({0}): {1}", n, oneFib(n));
  }
}
Output:
Fibonacci numbers 0..20: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
Fibonacci(1000): 43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875

C++

Using unsigned int, this version only works up to 48 before fib overflows.

#include <iostream>

int main()
{
        unsigned int a = 1, b = 1;
        unsigned int target = 48;
        for(unsigned int n = 3; n <= target; ++n)
        {
                unsigned int fib = a + b;
                std::cout << "F("<< n << ") = " << fib << std::endl;
                a = b;
                b = fib;
        }

        return 0;
}


Library: GMP

This version does not have an upper bound.

#include <iostream>
#include <gmpxx.h>

int main()
{
        mpz_class a = mpz_class(1), b = mpz_class(1);
        mpz_class target = mpz_class(100);
        for(mpz_class n = mpz_class(3); n <= target; ++n)
        {
                mpz_class fib = b + a;
                if ( fib < b )
                {
                        std::cout << "Overflow at " << n << std::endl;
                        break;
                }
                std::cout << "F("<< n << ") = " << fib << std::endl;
                a = b;
                b = fib;
        }
        return 0;
}

Version using transform:

#include <algorithm>
#include <vector>
#include <functional>
#include <iostream>
 
unsigned int fibonacci(unsigned int n) {
  if (n == 0) return 0;
  std::vector<int> v(n+1);
  v[1] = 1;
  transform(v.begin(), v.end()-2, v.begin()+1, v.begin()+2, std::plus<int>());
  // "v" now contains the Fibonacci sequence from 0 up
  return v[n];
}

Far-fetched version using adjacent_difference:

#include <numeric>
#include <vector>
#include <functional>
#include <iostream>

unsigned int fibonacci(unsigned int n) {
  if (n == 0) return 0;
  std::vector<int> v(n, 1);
  adjacent_difference(v.begin(), v.end()-1, v.begin()+1, std::plus<int>());
  // "array" now contains the Fibonacci sequence from 1 up
  return v[n-1];
}

Version which computes at compile time with metaprogramming:

#include <iostream>

template <int n> struct fibo
{
    enum {value=fibo<n-1>::value+fibo<n-2>::value};
};
 
template <> struct fibo<0>
{
    enum {value=0};
};

template <> struct fibo<1>
{
    enum {value=1};
};


int main(int argc, char const *argv[])
{
    std::cout<<fibo<12>::value<<std::endl;
    std::cout<<fibo<46>::value<<std::endl;
    return 0;
}

The following version is based on fast exponentiation:

#include <iostream>

inline void fibmul(int* f, int* g)
{
  int tmp = f[0]*g[0] + f[1]*g[1];
  f[1] = f[0]*g[1] + f[1]*(g[0] + g[1]);
  f[0] = tmp;
}

int fibonacci(int n)
{
  int f[] = { 1, 0 };
  int g[] = { 0, 1 };
  while (n > 0)
  {
    if (n & 1) // n odd
    {
      fibmul(f, g);
      --n;
    }
    else
    {
      fibmul(g, g);
      n >>= 1;
    }
  }
  return f[1];
}

int main()
{
  for (int i = 0; i < 20; ++i)
    std::cout << fibonacci(i) << " ";
  std::cout << std::endl;
}
Output:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

Using Zeckendorf Numbers

The nth fibonacci is represented as Zeckendorf 1 followed by n-1 zeroes. Here I define a class N which defines the operations increment ++() and comparison <=(other N) for Zeckendorf Numbers.

// Use Zeckendorf numbers to display Fibonacci sequence.
// Nigel Galloway October 23rd., 2012
int main(void) {
  char NG[22] = {'1',0};
  int x = -1;
  N G;
  for (int fibs = 1; fibs <= 20; fibs++) {
   for (;G <= N(NG); ++G) x++;
   NG[fibs] = '0';
   NG[fibs+1] = 0;
   std::cout << x << " ";
  }
  std::cout << std::endl;
  return 0;
}
Output:
1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946

Using Standard Template Library

Possibly less "Far-fetched version".

// Use Standard Template Library to display Fibonacci sequence.
// Nigel Galloway March 30th., 2013
#include <algorithm>
#include <iostream>
#include <iterator>
int main()
{
   int x = 1, y = 1;
   generate_n(std::ostream_iterator<int>(std::cout, " "), 21, [&]{int n=x; x=y; y+=n; return n;});
   return 0;
}
Output:

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946

Cat

define fib {
  dup 1 <=
    []
    [dup 1 - fib swap 2 - fib +]
  if
}

Chapel

iter fib() {
        var a = 0, b = 1;

        while true {
                yield a;
                (a, b) = (b, b + a);
        }
}

Chef

Stir-Fried Fibonacci Sequence.

An unobfuscated iterative implementation.
It prints the first N + 1 Fibonacci numbers,
where N is taken from standard input.

Ingredients.
0 g last
1 g this
0 g new
0 g input

Method.
Take input from refrigerator.
Put this into 4th mixing bowl.
Loop the input.
Clean the 3rd mixing bowl.
Put last into 3rd mixing bowl.
Add this into 3rd mixing bowl.
Fold new into 3rd mixing bowl.
Clean the 1st mixing bowl.
Put this into 1st mixing bowl.
Fold last into 1st mixing bowl.
Clean the 2nd mixing bowl.
Put new into 2nd mixing bowl.
Fold this into 2nd mixing bowl.
Put new into 4th mixing bowl.
Endloop input until looped.
Pour contents of the 4th mixing bowl into baking dish.

Serves 1.

Chez Scheme

(define fib (lambda (n) (cond ((> n 1) (+ (fib (- n 1)) (fib (- n 2)))) 
                              ((= n 1) 1) 
                              ((= n 0) 0))))

Clio

Clio is pure and functions are lazy and memoized by default

fn fib n:
  if n < 2: n
  else: (n - 1 -> fib) + (n - 2 -> fib)

[0:100] -> * fib -> * print

Clojure

Lazy Sequence

This is implemented idiomatically as an infinitely long, lazy sequence of all Fibonacci numbers:

(defn fibs []
  (map first (iterate (fn [[a b]] [b (+ a b)]) [0 1])))

Thus to get the nth one:

(nth (fibs) 5)

So long as one does not hold onto the head of the sequence, this is unconstrained by length.

The one-line implementation may look confusing at first, but on pulling it apart it actually solves the problem more "directly" than a more explicit looping construct.

(defn fibs []
  (map first ;; throw away the "metadata" (see below) to view just the fib numbers
       (iterate ;; create an infinite sequence of [prev, curr] pairs
         (fn [[a b]] ;; to produce the next pair, call this function on the current pair
           [b (+ a b)]) ;; new prev is old curr, new curr is sum of both previous numbers
         [0 1]))) ;; recursive base case: prev 0, curr 1

A more elegant solution is inspired by the Haskell implementation of an infinite list of Fibonacci numbers:

(def fib (lazy-cat [0 1] (map + fib (rest fib))))

Then, to see the first ten,

user> (take 10 fib)
(0 1 1 2 3 5 8 13 21 34)

Iterative

Here's a simple interative process (using a recursive function) that carries state along with it (as args) until it reaches a solution:

;; max is which fib number you'd like computed (0th, 1st, 2nd, etc.)
;; n is which fib number you're on for this call (0th, 1st, 2nd, etc.)
;; j is the nth fib number (ex. when n = 5, j = 5)
;; i is the nth - 1 fib number
(defn- fib-iter
  [max n i j]
  (if (= n max)
    j
    (recur max
           (inc n)
           j
           (+ i j))))

(defn fib
  [max]
  (if (< max 2)
    max
    (fib-iter max 1 0N 1N)))

"defn-" means that the function is private (for use only inside this library). The "N" suffixes on integers tell Clojure to use arbitrary precision ints for those.

Doubling Algorithm (Fast)

Based upon the doubling algorithm which computes in O(log (n)) time as described here https://www.nayuki.io/page/fast-fibonacci-algorithms Implementation credit: https://stackoverflow.com/questions/27466311/how-to-implement-this-fast-doubling-fibonacci-algorithm-in-clojure/27466408#27466408

(defn fib [n]
  (letfn [(fib* [n]
            (if (zero? n)
              [0 1]
              (let [[a b] (fib* (quot n 2))
                    c (*' a (-' (*' 2 b) a))
                    d (+' (*' b b) (*' a a))]
                (if (even? n)
                  [c d]
                  [d (+' c d)]))))]
    (first (fib* n))))

Recursive

A naive slow recursive solution:

(defn fib [n]
  (case n
    0 0
    1 1
    (+ (fib (- n 1))
       (fib (- n 2)))))

This can be improved to an O(n) solution, like the iterative solution, by memoizing the function so that numbers that have been computed are cached. Like a lazy sequence, this also has the advantage that subsequent calls to the function use previously cached results rather than recalculating.

(def fib
  (memoize
    (fn [n]
      (case n
        0 0
        1 1
        (+ (fib (- n 1))
           (fib (- n 2)))))))

Using core.async

(ns fib.core)
(require '[clojure.core.async
           :refer [<! >! >!! <!! timeout chan alt! go]])

(defn fib [c]
  (loop [a 0 b 1]
    (>!! c a)
    (recur b (+ a b))))


(defn -main []
  (let [c (chan)]
    (go (fib c))
    (dorun
      (for [i (range 10)]
        (println (<!! c))))))

CLU

% Generate Fibonacci numbers
fib = iter () yields (int)
    a: int := 0
    b: int := 1
    
    while true do
        yield (a)
        a, b := b, a+b
    end
end fib

% Grab the n'th value from an iterator 
nth = proc [T: type] (g: itertype () yields (T), n: int) returns (T)
    for v: T in g() do
        if n<=0 then return (v) end
        n := n-1
    end
end nth

% Print a few values
start_up = proc ()
    po: stream := stream$primary_output()
    
    % print values coming out of the fibonacci iterator
    % (which are generated one after the other without delay)
    count: int := 0
    for f: int in fib() do 
        stream$putl(po, "F(" || int$unparse(count) || ") = " || int$unparse(f))
        count := count + 1
        if count = 15 then break end
    end
    
    % print a few random fibonacci numbers
    % (to do this it has to restart at the beginning for each 
    % number, making it O(N))
    fibs: sequence[int] := sequence[int]$[20,30,50]
    for n: int in sequence[int]$elements(fibs) do
        stream$putl(po, "F(" || int$unparse(n) || ") = "
                             || int$unparse(nth[int](fib, n)))
    end
end start_up
Output:
F(0) = 0
F(1) = 1
F(2) = 1
F(3) = 2
F(4) = 3
F(5) = 5
F(6) = 8
F(7) = 13
F(8) = 21
F(9) = 34
F(10) = 55
F(11) = 89
F(12) = 144
F(13) = 233
F(14) = 377
F(20) = 6765
F(30) = 832040
F(50) = 12586269025

CMake

Iteration uses a while() loop. Memoization uses global properties.

set_property(GLOBAL PROPERTY fibonacci_0 0)
set_property(GLOBAL PROPERTY fibonacci_1 1)
set_property(GLOBAL PROPERTY fibonacci_next 2)

# var = nth number in Fibonacci sequence.
function(fibonacci var n)
  # If the sequence is too short, compute more Fibonacci numbers.
  get_property(next GLOBAL PROPERTY fibonacci_next)
  if(NOT next GREATER ${n})
    # a, b = last 2 Fibonacci numbers
    math(EXPR i "${next} - 2")
    get_property(a GLOBAL PROPERTY fibonacci_${i})
    math(EXPR i "${next} - 1")
    get_property(b GLOBAL PROPERTY fibonacci_${i})

    while(NOT next GREATER ${n})
      math(EXPR i "${a} + ${b}")  # i = next Fibonacci number
      set_property(GLOBAL PROPERTY fibonacci_${next} ${i})
      set(a ${b})
      set(b ${i})
      math(EXPR next "${next} + 1")
    endwhile()
    set_property(GLOBAL PROPERTY fibonacci_next ${next})
  endif()

  get_property(answer GLOBAL PROPERTY fibonacci_${n})
  set(${var} ${answer} PARENT_SCOPE)
endfunction(fibonacci)
# Test program: print 0th to 9th and 25th to 30th Fibonacci numbers.
set(s "")
foreach(i RANGE 0 9)
  fibonacci(f ${i})
  set(s "${s} ${f}")
endforeach(i)
set(s "${s} ... ")
foreach(i RANGE 25 30)
  fibonacci(f ${i})
  set(s "${s} ${f}")
endforeach(i)
message(${s})
 0 1 1 2 3 5 8 13 21 34 ... 75025 121393 196418 317811 514229 832040

COBOL

Iterative

Program-ID. Fibonacci-Sequence.
Data Division.
Working-Storage Section.
  01  FIBONACCI-PROCESSING.
    05  FIBONACCI-NUMBER  PIC 9(36)   VALUE 0.
    05  FIB-ONE           PIC 9(36)   VALUE 0.
    05  FIB-TWO           PIC 9(36)   VALUE 1.
  01  DESIRED-COUNT       PIC 9(4).
  01  FORMATTING.
    05  INTERM-RESULT     PIC Z(35)9.
    05  FORMATTED-RESULT  PIC X(36).
    05  FORMATTED-SPACE   PIC x(35).
Procedure Division.
  000-START-PROGRAM.
    Display "What place of the Fibonacci Sequence would you like (<173)? " with no advancing.
    Accept DESIRED-COUNT.
    If DESIRED-COUNT is less than 1
      Stop run.
    If DESIRED-COUNT is less than 2
      Move FIBONACCI-NUMBER to INTERM-RESULT
      Move INTERM-RESULT to FORMATTED-RESULT
      Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT
      Display FORMATTED-RESULT
      Stop run.
    Subtract 1 from DESIRED-COUNT.
    Move FIBONACCI-NUMBER to INTERM-RESULT.
    Move INTERM-RESULT to FORMATTED-RESULT.
    Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT.
    Display FORMATTED-RESULT.
    Perform 100-COMPUTE-FIBONACCI until DESIRED-COUNT = zero.
    Stop run.
  100-COMPUTE-FIBONACCI.
    Compute FIBONACCI-NUMBER = FIB-ONE + FIB-TWO.
    Move FIB-TWO to FIB-ONE.
    Move FIBONACCI-NUMBER to FIB-TWO.
    Subtract 1 from DESIRED-COUNT.
    Move FIBONACCI-NUMBER to INTERM-RESULT.
    Move INTERM-RESULT to FORMATTED-RESULT.
    Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT.
    Display FORMATTED-RESULT.

Recursive

Works with: GNU Cobol version 2.0
       >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. fibonacci-main.

DATA DIVISION.
WORKING-STORAGE SECTION.
01  num                                 PIC 9(6) COMP.
01  fib-num                             PIC 9(6) COMP.

PROCEDURE DIVISION.
    ACCEPT num
    CALL "fibonacci" USING CONTENT num RETURNING fib-num
    DISPLAY fib-num
    .
END PROGRAM fibonacci-main.

IDENTIFICATION DIVISION.
PROGRAM-ID. fibonacci RECURSIVE.

DATA DIVISION.
LOCAL-STORAGE SECTION.
01  1-before                            PIC 9(6) COMP.
01  2-before                            PIC 9(6) COMP.

LINKAGE SECTION.
01  num                                 PIC 9(6) COMP.

01  fib-num                             PIC 9(6) COMP BASED.

PROCEDURE DIVISION USING num RETURNING fib-num.
    ALLOCATE fib-num
    EVALUATE num
        WHEN 0
            MOVE 0 TO fib-num
        WHEN 1
            MOVE 1 TO fib-num
        WHEN OTHER
            SUBTRACT 1 FROM num
            CALL "fibonacci" USING CONTENT num RETURNING 1-before
            SUBTRACT 1 FROM num
            CALL "fibonacci" USING CONTENT num RETURNING 2-before
            ADD 1-before TO 2-before GIVING fib-num
    END-EVALUATE
    .
END PROGRAM fibonacci.

CoffeeScript

Analytic

fib_ana = (n) ->
    sqrt = Math.sqrt
    phi = ((1 + sqrt(5))/2)
    Math.round((Math.pow(phi, n)/sqrt(5)))

Iterative

fib_iter = (n) ->
    return n if n < 2
    [prev, curr] = [0, 1]
    [prev, curr] = [curr, curr + prev] for i in [1..n]
    curr

Recursive

fib_rec = (n) ->
  if n < 2 then n else fib_rec(n-1) + fib_rec(n-2)

Comefrom0x10

Recursion is is not possible in Comefrom0x10.

Iterative

stop = 6
a = 1
i = 1  # start
a      # print result

fib
  comefrom if i is 1  # start
  b = 1
  comefrom fib        # start of loop
  i = i + 1
  next_b = a + b
  a = b
  b = next_b

  comefrom fib if i > stop

Common Lisp

Note that Common Lisp uses bignums, so this will never overflow.

Iterative

(defun fibonacci-iterative (n &aux (f0 0) (f1 1))
  (case n
    (0 f0)
    (1 f1)
    (t (loop for n from 2 to n
             for a = f0 then b and b = f1 then result
             for result = (+ a b)
             finally (return result)))))

Simpler one:

(defun fibonacci (n)
  (let ((a 0) (b 1) (c n))
    (loop for i from 2 to n do
	 (setq c (+ a b)
	       a b
	       b c))
    c))

Not a function, just printing out the entire (for some definition of "entire") sequence with a for var = loop:

(loop for x = 0 then y and y = 1 then (+ x y) do (print x))

Recursive

(defun fibonacci-recursive (n)
  (if (< n 2)
      n
     (+ (fibonacci-recursive (- n 2)) (fibonacci-recursive (- n 1)))))


(defun fibonacci-tail-recursive ( n &optional (a 0) (b 1))
  (if (= n 0) 
      a 
      (fibonacci-tail-recursive (- n 1) b (+ a b))))

Tail recursive and squaring:

(defun fib (n &optional (a 1) (b 0) (p 0) (q 1))
    (if (= n 1) (+ (* b p) (* a q))
     (fib (ash n -1) 
          (if (evenp n) a (+ (* b q) (* a (+ p q))))
          (if (evenp n) b (+ (* b p) (* a q)))
          (+ (* p p) (* q q))
          (+ (* q q) (* 2 p q))))) ;p is Fib(2^n-1), q is Fib(2^n).

(print (fib 100000))

Alternate solution

I use Allegro CL 10.1

;; Project : Fibonacci sequence

(defun fibonacci (nr)
           (cond ((= nr 0) 1)
           ((= nr 1) 1)
           (t (+ (fibonacci (- nr 1))
           (fibonacci (- nr 2))))))
(format t "~a" "First 10 Fibonacci numbers") 
(dotimes (n 10) 
(if (< n 1) (terpri))
(if (< n 9) (format t "~a" " "))
(write(+ n 1)) (format t "~a" ": ")
(write (fibonacci n)) (terpri))

Output:

First 10 Fibonacci numbers
 1: 1
 2: 1
 3: 2
 4: 3
 5: 5
 6: 8
 7: 13
 8: 21
 9: 34
10: 55

Solution with methods and eql specializers

(defmethod fib (n)
  (declare ((integer 0 *) n))
  (+ (fib (- n 1))
     (fib (- n 2))))

(defmethod fib ((n (eql 0))) 0)

(defmethod fib ((n (eql 1))) 1)

List-based iterative

This solution uses a list to keep track of the Fibonacci sequence for 0 or a positive integer.

(defun fibo (n)
  (cond ((< n 0) nil)
        ((< n 2) n)
        (t (let ((leo '(1 0)))
             (loop for i from 2 upto n do
               (setf leo (cons (+ (first leo) 
                                  (second leo))
                               leo))
               finally (return (first leo)))))))
Output:
> (fibo 0)
0
> (fibo 1)
1
> (fibo 10)
55
> (fibo 100)
354224848179261915075
> (fibo 1000)
43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875
> (fibo -10)
NIL

List-based recursive

This solution computes Fibonacci numbers as either:

  1. a list starting from the first element;
  2. a single number;
  3. an interval from i-th to j-th element.


Options #2 and #3 can take negative parameters, but i (lowest index in range) must be greater than j (highest index in range).

Values are represented internally by a reversed list that grows from the head (and that's why we reverse it back when we return it).

(defparameter *fibo-start* '(1 1)) ; elements 1 and 2

;;; Helper functions
(defun grow-fibo (fibo)
    (cons (+ (first fibo) (second fibo)) fibo))

(defun generate-fibo (fibo n) ; n must be > 1
    (if (equal (list-length fibo) n)
        fibo
        (generate-fibo (grow-fibo fibo)  n)))

;;; User functions
(defun fibo (n)
    (cond ((= n 0) 0)
          ((= (abs n) 1) 1)
          (t (let ((result (first (generate-fibo *fibo-start* (abs n)))))
               (if (and (< n -1) (evenp n))
                 (- result)
                 result)))))

(defun fibo-list (n)
    (cond ((< n 1) nil)
          ((= n 1) '(1))
          (t (reverse (generate-fibo *fibo-start* n)))))

(defun fibo-range (lower upper)
   (if (<= upper lower)
     nil
     (reverse (generate-fibo
                 (list
                    (fibo (1+ lower))
                    (fibo  lower))
                 (1+ (- upper lower))))))
Output:
> (fibo 100)
354224848179261915075
> (fibo -150)
-9969216677189303386214405760200
> (fibo-list 20)
(1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765)
> (fibo-range -10 15)
(-55 34 -21 13 -8 5 -3 2 -1 1 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610)
> (fibo-range 0 20)
(0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765)

Computer/zero Assembly

To find the th Fibonacci number, set the initial value of count equal to –2 and run the program. The machine will halt with the answer stored in the accumulator. Since Computer/zero's word length is only eight bits, the program will not work with values of greater than 13.

loop:   LDA  y      ; higher No.
        STA  temp
        ADD  x      ; lower No.
        STA  y
        LDA  temp
        STA  x

        LDA  count
        SUB  one
        BRZ  done

        STA  count
        JMP  loop

done:   LDA  y
        STP

one:         1
count:       8      ; n = 10
x:           1
y:           1
temp:        0

Coq

Fixpoint rec_fib (m : nat) (a : nat) (b : nat) : nat :=
  match m with
    | 0 => a
    | S k => rec_fib k b (a + b)
  end.

Definition fib (n : nat) : nat :=
  rec_fib n 0 1 .

Corescript

print Fibonacci Sequence:
var previous = 1
var number = 0
var temp = (blank)

:fib
if number > 50000000000:kill
print (number)
set temp = (add number previous)
set previous = (number)
set number = (temp)
goto fib

:kill
stop

Cowgol

include "cowgol.coh";

sub fibonacci(n: uint32): (a: uint32) is
    a := 0;
    var b: uint32 := 1;
    while n > 0 loop
        var c := a + b;
        a := b;
        b := c;
        n := n - 1;
    end loop;
end sub;

# test
var i: uint32 := 0;
while i < 20 loop
    print_i32(fibonacci(i));
    print_char(' ');
    i := i + 1;
end loop;
print_nl();
Output:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

Crystal

Recursive

def fib(n)
  n < 2 ? n : fib(n - 1) + fib(n - 2)
end

Iterative

def fibIterative(n, prevFib = 0, fib = 1)
  return n if n < 2

  n.times do
    prevFib, fib = fib, prevFib + fib
  end

  prevFib
end

Tail Recursive

def fibTailRecursive(n, prevFib = 0, fib = 1)
  n == 0 ? prevFib : fibTailRecursive(n - 1, fib, prevFib + fib)
end

Analytic

def fibBinet(n)
  (((5 ** 0.5 + 1) / 2) ** n / 5 ** 0.5).round.to_i
end

D

Here are four versions of Fibonacci Number calculating functions. FibD has an argument limit of magnitude 84 due to floating point precision, the others have a limit of 92 due to overflow (long).The traditional recursive version is inefficient. It is optimized by supplying a static storage to store intermediate results. A Fibonacci Number generating function is added. All functions have support for negative arguments.

import std.stdio, std.conv, std.algorithm, std.math;

long sgn(alias unsignedFib)(int n) { // break sign manipulation apart
    immutable uint m = (n >= 0) ? n : -n;
    if (n < 0 && (n % 2 == 0))
        return -unsignedFib(m);
    else
        return unsignedFib(m);
}

long fibD(uint m) { // Direct Calculation, correct for abs(m) <= 84
    enum sqrt5r =  1.0L / sqrt(5.0L);         //  1 / sqrt(5)
    enum golden = (1.0L + sqrt(5.0L)) / 2.0L; // (1 + sqrt(5)) / 2
    return roundTo!long(pow(golden, m) * sqrt5r);
}

long fibI(in uint m) pure nothrow { // Iterative
    long thisFib = 0;
    long nextFib = 1;
    foreach (i; 0 .. m) {
        long tmp = nextFib;
        nextFib += thisFib;
        thisFib  = tmp;
    }
    return thisFib;
}

long fibR(uint m) { // Recursive
    return (m < 2) ? m : fibR(m - 1) + fibR(m - 2);
}

long fibM(uint m) { // memoized Recursive
    static long[] fib = [0, 1];
    while (m >= fib.length )
        fib ~= fibM(m - 2) + fibM(m - 1);
    return fib[m];
}

alias sgn!fibD sfibD;
alias sgn!fibI sfibI;
alias sgn!fibR sfibR;
alias sgn!fibM sfibM;

auto fibG(in int m) { // generator(?)
    immutable int sign = (m < 0) ? -1 : 1;
    long yield;
    
    return new class {
        final int opApply(int delegate(ref int, ref long) dg) {
            int idx = -sign; // prepare for pre-increment
            foreach (f; this)
                if (dg(idx += sign, f))
                    break;
            return 0;
        }
        
        final int opApply(int delegate(ref long) dg) {
            long f0, f1 = 1;
            foreach (p; 0 .. m * sign + 1) {
                if (sign == -1 && (p % 2 == 0))
                    yield = -f0;
                else
                    yield = f0;
                if (dg(yield)) break;
                auto temp = f1;
                f1 = f0 + f1;
                f0 = temp;
            }
            return 0;
        }
    };
}

void main(in string[] args) {
    int k = args.length > 1 ? to!int(args[1]) : 10;
    writefln("Fib(%3d) = ", k);
    writefln("D : %20d <- %20d + %20d",
             sfibD(k), sfibD(k - 1), sfibD(k - 2));
    writefln("I : %20d <- %20d + %20d",
             sfibI(k), sfibI(k - 1), sfibI(k - 2));
    if (abs(k) < 36 || args.length > 2)
        // set a limit for recursive version
        writefln("R : %20d <- %20d + %20d",
                 sfibR(k), sfibM(k - 1), sfibM(k - 2));
    writefln("O : %20d <- %20d + %20d",
             sfibM(k), sfibM(k - 1), sfibM(k - 2));
    foreach (i, f; fibG(-9))
        writef("%d:%d | ", i, f);
}
Output:

for n = 85

Fib( 85) = 
D :   259695496911122586 <-   160500643816367088 +    99194853094755497
I :   259695496911122585 <-   160500643816367088 +    99194853094755497
O :   259695496911122585 <-   160500643816367088 +    99194853094755497
0:0 | -1:1 | -2:-1 | -3:2 | -4:-3 | -5:5 | -6:-8 | -7:13 | -8:-21 | -9:34 | 

Matrix Exponentiation Version

import std.bigint;

T fibonacciMatrix(T=BigInt)(size_t n) {
    int[size_t.sizeof * 8] binDigits;
    size_t nBinDigits;
    while (n > 0) {
        binDigits[nBinDigits] = n % 2;
        n /= 2;
        nBinDigits++;
    }

    T x=1, y, z=1;
    foreach_reverse (b; binDigits[0 .. nBinDigits]) {
        if (b) {
            x = (x + z) * y;
            y = y ^^ 2 + z ^^ 2;
        } else {
            auto x_old = x;
            x = x ^^ 2 + y ^^ 2;
            y = (x_old + z) * y;
        }
        z = x + y;
    }

    return y;
}

void main() {
    10_000_000.fibonacciMatrix;
}

Faster Version

For N = 10_000_000 this is about twice faster (run-time about 2.20 seconds) than the matrix exponentiation version.

import std.bigint, std.math;

// Algorithm from: Takahashi, Daisuke,
// "A fast algorithm for computing large Fibonacci numbers".
// Information Processing Letters 75.6 (30 November 2000): 243-246.
// Implementation from:
// pythonista.wordpress.com/2008/07/03/pure-python-fibonacci-numbers
BigInt fibonacci(in ulong n)
in {
    assert(n > 0, "fibonacci(n): n must be > 0.");
} body {
    if (n <= 2)
        return 1.BigInt;
    BigInt F = 1;
    BigInt L = 1;
    int sign = -1;
    immutable uint n2 = cast(uint)n.log2.floor;
    auto mask = 2.BigInt ^^ (n2 - 1);
    foreach (immutable i; 1 .. n2) {
        auto temp = F ^^ 2;
        F = (F + L) / 2;
        F = 2 * F ^^ 2 - 3 * temp - 2 * sign;
        L = 5 * temp + 2 * sign;
        sign = 1;
        if (n & mask) {
            temp = F;
            F = (F + L) / 2;
            L = F + 2 * temp;
            sign = -1;
        }
        mask /= 2;
    }
    if ((n & mask) == 0) {
        F *= L;
    } else {
        F = (F + L) / 2;
        F = F * L - sign;
    }
    return F;
}

void main() {
    10_000_000.fibonacci;
}

Dart

int fib(int n) {
  if (n==0 || n==1) {
    return n;
  }
  var prev=1;
  var current=1;
  for (var i=2; i<n; i++) {
    var next = prev + current;
    prev = current;
    current = next;    
  }
  return current;
}

int fibRec(int n) => n==0 || n==1 ? n : fibRec(n-1) + fibRec(n-2);

main() {
  print(fib(11));
  print(fibRec(11));
}

Datalog

Simple recurive implementation for Souffle.

.decl Fib(i:number, x:number)
Fib(0, 0). 
Fib(1, 1). 
Fib(i+2,x+y) :- Fib(i+1, x), Fib(i, y), i+2<=40, i+2>=2.
Fib(i-2,y-x) :- Fib(i-1, x), Fib(i, y), i-2>=-40, i-2<0.

DBL

;
;       Fibonacci sequence for DBL version 4 by Dario B.
;
        RECORD

FIB1,  D10
FIB2,  D10
FIBN,  D10

J,     D5
A2,    A2
A5,    A5
                                PROC
;----------------------------------------------------------------
        XCALL FLAGS (0007000000,1)         ;Suppress STOP message

        OPEN (1,O,'TT:')
        DISPLAY (1,'First 10 Fibonacci Numbers:',10)
 
        FIB2=1

        FOR J=1 UNTIL 10
        DO BEGIN
                FIBN=FIB1+FIB2

                A2=J,'ZX'
                A5=FIBN,'ZZZZX'
                DISPLAY (1,A2,' : ',A5,10)

                FIB1=FIB2
                FIB2=FIBN
            END
 
        CLOSE 1
END

Dc

This needs a modern Dc with r (swap) and # (comment). It easily can be adapted to an older Dc, but it will impact readability a lot.

[               # todo: n(<2) -- 1 and break 2 levels
  d -           # 0
  1 +           # 1
  q
] s1

[               # todo: n(>-1) -- F(n)
  d 0=1         # n(!=0)
  d 1=1         # n(!in {0,1})
  2 - d 1 +     # (n-2) (n-1)
  lF x          # (n-2) F(n-1)
  r             # F(n-1) (n-2)
  lF x          # F(n-1)+F(n-2)
  +
] sF

33 lF x f
Output:
5702887

Delphi

Iterative

function FibonacciI(N: Word): UInt64;
var
  Last, New: UInt64;
  I: Word;
begin
  if N < 2 then
    Result := N
  else begin
    Last := 0;
    Result := 1;
    for I := 2 to N do
    begin
      New := Last + Result;
      Last := Result;
      Result := New;
    end;
  end;
end;

Recursive

function Fibonacci(N: Word): UInt64;
begin
  if N < 2 then
    Result := N
  else
   Result := Fibonacci(N - 1) + Fibonacci(N - 2);
end;

Matrix

Algorithm is based on

.
function fib(n: Int64): Int64;

  type TFibMat = array[0..1] of array[0..1] of Int64;
	
  function FibMatMul(a,b: TFibMat): TFibMat;
  var i,j,k: integer;
      tmp: TFibMat;
  begin
    for i := 0 to 1 do
      for j := 0 to 1 do
      begin
	tmp[i,j] := 0;
	for k := 0 to 1 do tmp[i,j] := tmp[i,j] + a[i,k] * b[k,j];
      end;
    FibMatMul := tmp;
  end;
	
  function FibMatExp(a: TFibMat; n: Int64): TFibmat;
  begin
    if n <= 1 then fibmatexp := a
    else if (n mod 2 = 0) then FibMatExp := FibMatExp(FibMatMul(a,a), n div 2)
    else if (n mod 2 = 1) then FibMatExp := FibMatMul(a, FibMatExp(FibMatMul(a,a), n div 2));
  end;

var 
  matrix: TFibMat;
	
begin
  matrix[0,0] := 1;
  matrix[0,1] := 1;
  matrix[1,0] := 1;
  matrix[1,1] := 0;
  if n > 1 then
    matrix := fibmatexp(matrix,n-1);
  fib := matrix[0,0];
end;

DIBOL-11

    ;     Redone to include the first two values that
    ;     are noot computed.

      START    ;First 15 Fibonacci NUmbers


      RECORD
              FIB1,    D10,   0
              FIB2,    D10,   1
              FIBNEW,  D10
              LOOPCNT, D2,    3

       RECORD HEADER
,            A32, "First 15 Fibonacci Numbers."

       RECORD OUTPUT
             LOOPOUT, A2
,         A3, " : "
              FIBOUT, A10

      PROC

      OPEN(8,O,'TT:')

      WRITES(8,HEADER)

;   The First Two are given.

        FIBOUT = 0
        LOOPOUT = 1
      WRITES(8,OUTPUT)
        FIBOUT = 1
        LOOPOUT = 2
      WRITES(8,OUTPUT)

;   The Rest are Computed.
      
     LOOP,
             FIBNEW = FIB1 + FIB2
             LOOPOUT = LOOPCNT, 'ZX'
             FIBOUT = FIBNEW, 'ZZZZZZZZZX'

             WRITES(8,OUTPUT)

             FIB1 = FIB2
             FIB2 = FIBNEW
             
             LOOPCNT = LOOPCNT + 1
             IF LOOPCNT .LE. 15 GOTO LOOP

             CLOSE 8
             END

DWScript

function fib(N : Integer) : Integer;
begin
  if N < 2 then Result := 1
  else Result := fib(N-2) + fib(N-1);
End;

Dyalect

func fib(n) {
    if n < 2 {
        return n
    } else {
        return fib(n - 1) + fib(n - 2)
    }
}

print(fib(30))

E

def fib(n) {
    var s := [0, 1]
    for _ in 0..!n { 
        def [a, b] := s
        s := [b, a+b]
    }
    return s[0]
}

(This version defines fib(0) = 0 because OEIS A000045 does.)

EasyLang

func fib n .
   if n < 2
      return n
   .
   prev = 0
   val = 1
   for i = 2 to n
      h = prev + val
      prev = val
      val = h
   .
   return val
.
print fib 36

Recursive (inefficient):

func fib n .
   if n < 2
      return n
   .
   return fib (n - 2) + fib (n - 1)
.
print fib 36

EchoLisp

Use memoization with the recursive version.

(define (fib n) 
    (if (< n 2) n 
    (+ (fib (- n 2)) (fib (1- n)))))

(remember 'fib #(0 1))

(for ((i 12)) (write (fib i)))
0 1 1 2 3 5 8 13 21 34 55 89

ECL

Analytic

//Calculates Fibonacci sequence up to n steps using Binet's closed form solution


FibFunction(UNSIGNED2 n) := FUNCTION
	REAL Sqrt5 := Sqrt(5); 
	REAL Phi := (1+Sqrt(5))/2;
	REAL Phi_Inv := 1/Phi; 
	UNSIGNED FibValue := ROUND( ( POWER(Phi,n)-POWER(Phi_Inv,n) ) /Sqrt5); 
	RETURN FibValue; 
	END;  

 FibSeries(UNSIGNED2 n) := FUNCTION
 
 Fib_Layout := RECORD
 UNSIGNED5 FibNum;
 UNSIGNED5 FibValue; 
 END; 
 
 FibSeq := DATASET(n+1,
  TRANSFORM 
 ( Fib_Layout 
 , SELF.FibNum := COUNTER-1
 , SELF.FibValue := IF(SELF.FibNum<2,SELF.FibNum, FibFunction(SELF.FibNum) )
 ) 
 ); 
 
 RETURN FibSeq; 
 
 END; }

EDSAC order code

This program calculates the nth—by default the tenth—number in the Fibonacci sequence and displays it (in binary) in the first word of storage tank 3.

[ Fibonacci sequence
  ==================
  
  A program for the EDSAC
  
  Calculates the nth Fibonacci
  number and displays it at the
  top of storage tank 3
  
  The default value of n is 10
  
  To calculate other Fibonacci
  numbers, set the starting value
  of the count to n-2
  
  Works with Initial Orders 2 ]


        T56K  [ set load point  ]
        GK    [ set theta       ]
        
[ Orders ]

[  0 ]  T20@  [ a = 0           ]
        A17@  [ a += y          ]
        U18@  [ temp = a        ]
        A16@  [ a += x          ]
        T17@  [ y = a; a = 0    ]
        A18@  [ a += temp       ]
        T16@  [ x = a; a = 0    ]
        
        A19@  [ a = count       ]
        S15@  [ a -= 1          ]
        U19@  [ count = a       ]
        E@    [ if a>=0 go to θ ]
        
        T20@  [ a = 0           ]
        A17@  [ a += y          ]
        T96F  [ C(96) = a; a = 0]
        
        ZF    [ halt ]
        
[ Data ]
        
[ 15 ]  P0D   [ const: 1        ]
[ 16 ]  P0F   [ var: x = 0      ]
[ 17 ]  P0D   [ var: y = 1      ]
[ 18 ]  P0F   [ var: temp = 0   ]
[ 19 ]  P4F   [ var: count = 8  ]
[ 20 ]  P0F   [ used to clear a ]

        EZPF  [ begin execution ]
Output:
00000000000110111

Eiffel

class
	APPLICATION

create
	make

feature

	fibonacci (n: INTEGER): INTEGER
		require
			non_negative: n >= 0
		local
			i, n2, n1, tmp: INTEGER
		do
			n2 := 0
			n1 := 1
			from
				i := 1
			until
				i >= n
			loop
				tmp := n1
				n1 := n2 + n1
				n2 := tmp
				i := i + 1
			end
			Result := n1
			if n = 0 then
				Result := 0
			end
		end

feature {NONE} -- Initialization

	make
			-- Run application.
		do
			print (fibonacci (0))
			print (" ")
			print (fibonacci (1))
			print (" ")
			print (fibonacci (2))
			print (" ")
			print (fibonacci (3))
			print (" ")
			print (fibonacci (4))
			print ("%N")
		end

end

Ela

Tail-recursive function:

fib = fib' 0 1           
      where fib' a b 0 = a                 
            fib' a b n = fib' b (a + b) (n - 1)

Infinite (lazy) list:

fib = fib' 1 1
      where fib' x y = & x :: fib' y (x + y)

Elena

Translation of: Smalltalk

ELENA 6.x :

import extensions;
 
fibu(n)
{
    int[] ac := new int[]{ 0,1 };
    if (n < 2) 
    {
        ^ ac[n] 
    }
    else
    {
        for(int i := 2; i <= n; i+=1)
        {
            int t := ac[1];
            ac[1] := ac[0] + ac[1];
            ac[0] := t
        };
 
        ^ ac[1]
    }
}
 
public program()
{
    for(int i := 0; i <= 10; i+=1)
    {
        console.printLine(fibu(i))
    }
}
Output:
0
1
1
2
3
5
8
13
21
34
55

Alternative version using yieldable method

import extensions;

public FibonacciGenerator
{
    yieldable next()
    {
        long n_2 := 1l; 
        long n_1 := 1l;

        $yield n_2;             
        $yield n_1;

        while(true)
        {
            long n := n_2 + n_1;

            $yield n;

            n_2 := n_1;
            n_1 := n
        }
    }
}

public program()
{
    auto e := new FibonacciGenerator();
    
    for(int i := 0; i < 10; i += 1) {
        console.printLine(e.next())
    };
    
    console.readChar()
}

Elixir

defmodule Fibonacci do
    def fib(0), do: 0
    def fib(1), do: 1
    def fib(n), do: fib(0, 1, n-2)
    
    def fib(_, prv, -1), do: prv
    def fib(prvprv, prv, n) do
        next = prv + prvprv
        fib(prv, next, n-1)
    end
end

IO.inspect Enum.map(0..10, fn i-> Fibonacci.fib(i) end)

Using Stream:

Stream.unfold({0,1}, fn {a,b} -> {a,{b,a+b}} end) |> Enum.take(10)
Output:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

Elm

Naïve recursive implementation.

fibonacci : Int -> Int
fibonacci n = if n < 2 then
        n
    else
        fibonacci(n - 2) + fibonacci(n - 1)


version 2

fib : Int -> number
fib n =
   case n of
      0 -> 0
      1 -> 1
      _ -> fib (n-1) + fib (n-2)
Output:
elm repl
> fib 40
102334155 : number

> List.map (\elem -> fib elem) (List.range 1 40)
[1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,
4181,6765,10946,17711,28657,46368,75025,121393,196418,
317811,514229,832040,1346269,2178309,3524578,5702887,
9227465,14930352,24157817,39088169,63245986,102334155]
    : List number

Emacs Lisp

version 1

(defun fib (n a b c)
  (cond
   ((< c n) (fib n b (+ a b) (+ 1 c)))
   ((= c n) b)
   (t a)))

(defun fibonacci (n)
  (if (< n 2)
      n
    (fib n 0 1 1)))

version 2

(defun fibonacci (n)
  (let (vec i j k)
    (if (< n 2)
        n
      (setq vec (make-vector (+ n 1) 0)
            i 0
            j 1
            k 2)
      (setf (aref vec 1) 1)
      (while (<= k n)
        (setf (aref vec k) (+ (elt vec i) (elt vec j)))
        (setq i (1+ i)
              j (1+ j)
              k (1+ k)))
      (elt vec n))))

Eval:

(insert
 (mapconcat (lambda (n) (format "%d" (fibonacci n)))
            (number-sequence 0 15) " "))
Output:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610

Erlang

Recursive

-module(fib).
-export([fib/1]).

fib(0) -> 0;
fib(1) -> 1;
fib(N) -> fib(N-1) + fib(N-2).

Iterative

-module(fiblin).
-export([fib/1])

fib(0) -> 0;
fib(1) -> 1;
fib(2) -> 1;
fib(3) -> 2;
fib(4) -> 3;
fib(5) -> 5;

fib(N) when is_integer(N) -> fib(N - 6, 5, 8).
fib(N, A, B) -> if N < 1 -> B; true -> fib(N-1, B, A+B) end.

Evaluate:

io:write([fiblin:fib(X) || X <- lists:seq(1,10) ]).

Output:

   
[1,1,2,3,5,8,13,21,34,55]ok

Iterative 2

fib(N) -> fib(N, 0, 1).

fib(0, Result, _Next) -> Result;
fib(Iter, Result, Next) -> fib(Iter-1, Next, Result+Next).

ERRE

!-------------------------------------------
! derived from my book "PROGRAMMARE IN ERRE"
! iterative solution
!-------------------------------------------

PROGRAM FIBONACCI

!$DOUBLE

!VAR F1#,F2#,TEMP#,COUNT%,N%

BEGIN    !main
   INPUT("Number",N%)
   F1=0
   F2=1
   REPEAT
      TEMP=F2
      F2=F1+F2
      F1=TEMP
      COUNT%=COUNT%+1
   UNTIL COUNT%=N%
   PRINT("FIB(";N%;")=";F2)

   ! Obviously a FOR loop or a WHILE loop can
   ! be used to solve this problem

END PROGRAM
Output:
Number? 20
FIB( 20 )= 6765

Euphoria

'Recursive' version

Works with: Euphoria version any version
function fibor(integer n)
  if n<2 then return n end if
  return fibor(n-1)+fibor(n-2)
end function

'Iterative' version

Works with: Euphoria version any version
function fiboi(integer n)
integer f0=0, f1=1, f  
  if n<2 then return n end if
  for i=2 to n do
    f=f0+f1
    f0=f1
    f1=f   
  end for
  return f
end function

'Tail recursive' version

Works with: Euphoria version 4.0.0
function fibot(integer n, integer u = 1, integer s = 0)
  if n < 1 then
    return s
  else
    return fibot(n-1,u+s,u)
  end if
end function

-- example:
? fibot(10) -- says 55

'Paper tape' version

Works with: Euphoria version 4.0.0
include std/mathcons.e -- for PINF constant

enum ADD, MOVE, GOTO, OUT, TEST, TRUETO

global sequence tape = { 0, 
			 1, 
		       { ADD, 2, 1 }, 
		       { TEST, 1, PINF }, 
		       { TRUETO, 0 }, 
		       { OUT, 1, "%.0f\n" }, 
		       { MOVE, 2, 1 }, 
		       { MOVE, 0, 2 }, 
		       { GOTO, 3  } }

global integer ip
global integer test
global atom accum

procedure eval( sequence cmd )
	atom i = 1
	while i <= length( cmd ) do
		switch cmd[ i ] do
			case ADD then
				accum = tape[ cmd[ i + 1 ] ] + tape[ cmd[ i + 2 ] ]
				i += 2

			case OUT then
				printf( 1, cmd[ i + 2], tape[ cmd[ i + 1 ] ] ) 
				i += 2

			case MOVE then
				if cmd[ i + 1 ] = 0 then
					tape[ cmd[ i + 2 ] ] = accum
				else
					tape[ cmd[ i + 2 ] ] = tape[ cmd[ i + 1 ] ]
				end if
				i += 2

			case GOTO then
				ip = cmd[ i + 1 ] - 1 -- due to ip += 1 in main loop
				i += 1

			case TEST then
				if tape[ cmd[ i + 1 ] ] = cmd[ i + 2 ] then
					test = 1
				else
					test = 0
				end if
				i += 2

			case TRUETO then
				if test then
					if cmd[ i + 1 ] = 0 then
						abort(0)
					else
						ip = cmd[ i + 1 ] - 1
					end if
				end if

		end switch
		i += 1
	end while
end procedure

test = 0
accum = 0
ip = 1

while 1 do

	-- embedded sequences (assumed to be code) are evaluated
	-- atoms (assumed to be data) are ignored

	if sequence( tape[ ip ] ) then
		eval( tape[ ip ] ) 
	end if
	ip += 1
end while

Excel

LAMBDA

Binding the name FIBONACCI to the following lambda in the Excel worksheet Name Manager:

(See The LAMBDA worksheet function)

FIBONACCI
=LAMBDA(n,
    APPLYN(n - 2)(
        LAMBDA(xs,
            APPENDROWS(xs)(
                SUM(
                    LASTNROWS(2)(xs)
                )
            )
        )
    )({1;1})
)

And assuming that the following names are also bound to reusable generic lambdas in the Name manager:

APPENDROWS
=LAMBDA(xs,
    LAMBDA(ys,
        LET(
            nx, ROWS(xs),
            rowIndexes, SEQUENCE(nx + ROWS(ys)),
            colIndexes, SEQUENCE(
                1,
                MAX(COLUMNS(xs), COLUMNS(ys))
            ),

            IFERROR(
                IF(rowIndexes <= nx,
                    INDEX(xs, rowIndexes, colIndexes),
                    INDEX(ys, rowIndexes - nx, colIndexes)
                ),
                NA()
            )
        )
    )
)


APPLYN
=LAMBDA(n,
    LAMBDA(f,
        LAMBDA(x,
            IF(0 < n,
                APPLYN(n - 1)(f)(
                    f(x)
                ),
                x
            )
        )
    )
)

LASTNROWS
=LAMBDA(n,
    LAMBDA(xs,
        LET(
            nRows, COUNTA(xs),
            x, MIN(nRows, n),

            IF(0 < n,
                INDEX(
                    xs,
                    SEQUENCE(
                        x, 1,
                        1 + nRows - x,  1
                    )
                ),
                NA()
            )
        )
    )
)
Output:

The FIBONACCI(n) lambda defines a column of integers.

Here we obtain a row, by composing FIBONACCI with the built-in TRANSPOSE function:

fx =TRANSPOSE(FIBONACCI(15))
A B C D E F G H I J K L M N O P
1
2 15 Fibonacci terms: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610

Or as a fold, obtaining just the Nth term of the Fibonacci series:

FIBONACCI2
=LAMBDA(n,
    INDEX(
        FOLDL(
            LAMBDA(ab,
                LAMBDA(_,
                    APPEND(INDEX(ab, 2))(SUM(ab))
                )
            )
        )({0;1})(
            ENUMFROMTO(1)(n)
        ),
        1
    )
)

Assuming the following generic bindings in the Excel worksheet Name manager:

APPEND
=LAMBDA(xs,
    LAMBDA(ys,
        LET(
            nx, ROWS(xs),
            rowIndexes, SEQUENCE(nx + ROWS(ys)),
            colIndexes, SEQUENCE(
                1,
                MAX(COLUMNS(xs), COLUMNS(ys))
            ),
            IF(rowIndexes <= nx,
                INDEX(xs, rowIndexes, colIndexes),
                INDEX(ys, rowIndexes - nx, colIndexes)
            )
        )
    )
)


ENUMFROMTO
=LAMBDA(a,
    LAMBDA(z,
        SEQUENCE(1 + z - a, 1, a, 1)
    )
)


FOLDL
=LAMBDA(op,
    LAMBDA(a,
        LAMBDA(xs,
            IF(
                2 > ROWS(xs),
                op(a)(xs),
                FOLDL(op)(
                    op(a)(
                        HEAD(xs)
                    )
                )(
                    TAIL(xs)
                )
            )
        )
    )
)


HEAD
=LAMBDA(xs,
    INDEX(xs, 1, SEQUENCE(1, COLUMNS(xs)))
)


TAIL
=LAMBDA(xs,
    INDEX(
        xs,
        SEQUENCE(ROWS(xs) - 1, 1, 2, 1),
        SEQUENCE(1, COLUMNS(xs))
    )
)
Output:
fx =FIBONACCI2(A2)
A B
1 N Fibonacci
2 32 2178309
3 64 10610209857723

F#

This is a fast [tail-recursive] approach using the F# big integer support:

let fibonacci n : bigint =
  let rec f a b n =
    match n with
    | 0 -> a
    | 1 -> b
    | n -> (f b (a + b) (n - 1))
  f (bigint 0) (bigint 1) n
> fibonacci 100;;
val it : bigint = 354224848179261915075I

Lazy evaluated using sequence workflow:

let rec fib = seq { yield! [0;1];
                    for (a,b) in Seq.zip fib (Seq.skip 1 fib) -> a+b}

The above is extremely slow due to the nested recursions on sequences, which aren't very efficient at the best of times. The above takes seconds just to compute the 30th Fibonacci number!

Lazy evaluation using the sequence unfold anamorphism is much much better as to efficiency:

let fibonacci = Seq.unfold (fun (x, y) -> Some(x, (y, x + y))) (0I,1I)
fibonacci |> Seq.nth 10000

Approach similar to the Matrix algorithm in C#, with some shortcuts involved. Since it uses exponentiation by squaring, calculations of fib(n) where n is a power of 2 are particularly quick. Eg. fib(2^20) was calculated in a little over 4 seconds on this poster's laptop.

open System
open System.Diagnostics
open System.Numerics

/// Finds the highest power of two which is less than or equal to a given input.
let inline prevPowTwo (x : int) =
    let mutable n = x
    n <- n - 1
    n <- n ||| (n >>> 1)
    n <- n ||| (n >>> 2)
    n <- n ||| (n >>> 4)
    n <- n ||| (n >>> 8)
    n <- n ||| (n >>> 16)
    n <- n + 1
    match x with
    | x when x = n -> x
    | _ -> n/2

/// Evaluates the nth Fibonacci number using matrix arithmetic and
/// exponentiation by squaring.
let crazyFib (n : int) =
    let powTwo = prevPowTwo n

    /// Applies 2n rule repeatedly until another application of the rule would
    /// go over the target value (or the target value has been reached).
    let rec iter1 i q r s =
        match i with
        | i when i < powTwo ->
            iter1 (i*2) (q*q + r*r) (r * (q+s)) (r*r + s*s)
        | _ -> i, q, r, s

    /// Applies n+1 rule until the target value is reached.
    let rec iter2 (i, q, r, s) =
        match i with
        | i when i < n -> 
            iter2 ((i+1), (q+r), q, r)
        | _ -> q

    match n with
    | 0 -> 1I
    | _ ->
        iter1 1 1I 1I 0I
        |> iter2

Factor

Iterative

: fib ( n -- m )
    dup 2 < [
        [ 0 1 ] dip [ swap [ + ] keep ] times
        drop
    ] unless ;

Recursive

: fib ( n -- m )
    dup 2 < [
        [ 1 - fib ] [ 2 - fib ] bi +
    ] unless ;

Tail-Recursive

: fib2 ( x y n -- a )
  dup 1 <
    [ 2drop ]
    [ [ swap [ + ] keep ] dip 1 - fib2 ]
  if ;
: fib ( n -- m ) [ 0 1 ] dip fib2 ;

Matrix

Translation of: Ruby
USE: math.matrices

: fib ( n -- m )
    dup 2 < [
        [ { { 0 1 } { 1 1 } } ] dip 1 - m^n
        second second
    ] unless ;

Falcon

Iterative

function fib_i(n)

    if n < 2: return n

    fibPrev = 1
    fib = 1
    for i in [2:n]
        tmp = fib
        fib += fibPrev
        fibPrev = tmp
    end
    return fib
end

Recursive

function fib_r(n)
    if n < 2 :  return n
    return fib_r(n-1) + fib_r(n-2)
end

Tail Recursive

function fib_tr(n)
    return fib_aux(n,0,1)       
end
function fib_aux(n,a,b)
   switch n
      case 0 : return a
      default: return fib_aux(n-1,a+b,a)
   end
end

FALSE

[[$0=~][1-@@\$@@+\$44,.@]#]f:
20n: {First 20 numbers}
0 1 n;f;!%%44,. {Output: "0,1,1,2,3,5..."}

Fancy

class Fixnum {
  def fib {
    match self -> {
      case 0 -> 0
      case 1 -> 1
      case _ -> self - 1 fib + (self - 2 fib)
    }
  }
}

15 times: |x| {
  x fib println
}

Fantom

Ints have a limit of 64-bits, so overflow errors occur after computing Fib(92) = 7540113804746346429.

class Main
{
  static Int fib (Int n) 
  {
    if (n < 2) return n
    fibNums := [1, 0]
    while (fibNums.size <= n)
    {
      fibNums.insert (0, fibNums[0] + fibNums[1])
    }
    return fibNums.first
  }

  public static Void main ()
  {
    20.times |n| 
    {
      echo ("Fib($n) is ${fib(n)}")
    }
  }
}

Fe

Recursive:

(= fib (fn (n)
  (if (< n 2) n
    (+ (fib (- n 1)) (fib (- n 2))))))

Iterative:

(= fib (fn (n)
  (let p0 0)
  (let p1 1)
  (while (< 0 n)
    (= n (- n 1))
    (let tmp (+ p0 p1)) 
    (= p0 p1)
    (= p1 tmp))
  p0))

Fermat

Func Fibonacci(n) = if n<0 then -(-1)^n*Fibonacci(-n) else if n<2 then n else 
    Array fib[n+1];
    fib[1] := 0;
    fib[2] := 1;
    for i = 2, n do 
    fib[i+1]:=fib[i]+fib[i-1]
    od;
    Return(fib[n+1]);
    fi;
    fi;
    .

Fexl

# (fib n) = the nth Fibonacci number
\fib=
    (
    \loop==
        (\x\y\n
        le n 0 x;
        \z=(+ x y)
        \n=(- n 1)
        loop y z n
        )
    loop 0 1
    )


# Now test it:
for 0 20 (\n say (fib n))
Output:
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765

Fish

Outputs Fibonacci numbers until stopped.

10::n' 'o&+&$10.

FOCAL

01.10 TYPE "FIBONACCI NUMBERS" !
01.20 ASK "N =", N
01.30 SET A=0
01.40 SET B=1
01.50 FOR I=2,N; DO 2.0
01.60 TYPE "F(N) ", %8, B, !
01.70 QUIT

02.10 SET T=B
02.20 SET B=A+B
02.30 SET A=T
Output:
FIBONACCI NUMBERS
N =:20
F(N) =    6765

Forth

: fib ( n -- fib )
  0 1 rot 0 ?do  over + swap  loop drop ;

Or, for negative-index support:

: fib ( n -- Fn ) 0 1 begin
  rot dup 0 = if drop drop exit then
  dup 0 > if   1 - rot rot dup rot +
          else 1 + rot rot over - swap then 
again ;

Since there are only a fixed and small amount of Fibonacci numbers that fit in a machine word, this FORTH version creates a table of Fibonacci numbers at compile time. It stops compiling numbers when there is arithmetic overflow (the number turns negative, indicating overflow.)

: F-start,  here 1 0 dup , ;
: F-next,   over + swap
            dup 0> IF  dup , true  ELSE  false  THEN ;

: computed-table  ( compile: 'start 'next / run: i -- x )
   create
      >r execute
      BEGIN  r@ execute not  UNTIL  rdrop
   does> 
       swap cells + @ ;

' F-start, ' F-next,  computed-table fibonacci 2drop
here swap - cell/ Constant #F/64   \ # of fibonacci numbers generated

16 fibonacci . 987  ok
#F/64 . 93  ok
92 fibonacci . 7540113804746346429  ok   \ largest number generated.

Fortran

FORTRAN IV

C     FIBONACCI SEQUENCE - FORTRAN IV
      NN=46
      DO 1 I=0,NN
    1 WRITE(*,300) I,IFIBO(I)
  300 FORMAT(1X,I2,1X,I10)
      END
C
      FUNCTION IFIBO(N)
      IF(N) 9,1,2
    1 IFN=0
      GOTO 9
    2 IF(N-1) 9,3,4
    3 IFN=1
      GOTO 9
    4 IFNM1=0
      IFN=1
      DO 5 I=2,N
      IFNM2=IFNM1
      IFNM1=IFN
    5 IFN=IFNM1+IFNM2
    9 IFIBO=IFN
      END
Output:
  0          0
  1          1
  2          1
  3          2
  4          3
  5          5
  6          8
  7         13
  8         21
  9         34
 10         55
...
 45 1134903170
 46 1836311903

FORTRAN 77

      FUNCTION IFIB(N)
      IF (N.EQ.0) THEN
        ITEMP0=0
      ELSE IF (N.EQ.1) THEN
        ITEMP0=1
      ELSE IF (N.GT.1) THEN
        ITEMP1=0
        ITEMP0=1
        DO 1 I=2,N
          ITEMP2=ITEMP1
          ITEMP1=ITEMP0
          ITEMP0=ITEMP1+ITEMP2
    1   CONTINUE
      ELSE
        ITEMP1=1
        ITEMP0=0
        DO 2 I=-1,N,-1
          ITEMP2=ITEMP1
          ITEMP1=ITEMP0
          ITEMP0=ITEMP2-ITEMP1
    2   CONTINUE
      END IF
      IFIB=ITEMP0
      END

Test program

      EXTERNAL IFIB
      CHARACTER*10 LINE
      PARAMETER ( LINE = '----------' )
      WRITE(*,900) 'N', 'F[N]', 'F[-N]'
      WRITE(*,900) LINE, LINE, LINE
      DO 1 N = 0, 10
        WRITE(*,901) N, IFIB(N), IFIB(-N)
    1 CONTINUE
  900 FORMAT(3(X,A10))
  901 FORMAT(3(X,I10))
      END
Output:
          N       F[N]      F[-N]
 ---------- ---------- ----------
          0          0          0
          1          1          1
          2          1         -1
          3          2          2
          4          3         -3
          5          5          5
          6          8         -8
          7         13         13
          8         21        -21
          9         34         34
         10         55        -55

Recursive

In ISO Fortran 90 or later, use a RECURSIVE function:

module fibonacci
contains
    recursive function fibR(n) result(fib)
        integer, intent(in) :: n
        integer             :: fib
        
        select case (n)
            case (:0);      fib = 0
            case (1);       fib = 1
            case default;   fib = fibR(n-1) + fibR(n-2)
        end select
    end function fibR

Iterative

In ISO Fortran 90 or later:

    function fibI(n)
        integer, intent(in) :: n
        integer, parameter :: fib0 = 0, fib1 = 1
        integer            :: fibI, back1, back2, i
 
        select case (n)
            case (:0);      fibI = fib0
            case (1);       fibI = fib1
     
            case default
                fibI = fib1
                back1 = fib0
                do i = 2, n
                    back2 = back1
                    back1 = fibI
                    fibI   = back1 + back2
                end do
         end select
    end function fibI
end module fibonacci

Test program

program fibTest
    use fibonacci
    
    do i = 0, 10
        print *, fibr(i), fibi(i)
    end do 
end program fibTest
Output:
0 0
1 1
1 1
2 2
3 3
5 5
8 8
13 13
21 21
34 34
55 55

Free Pascal

See also: Pascal

type
	/// domain for Fibonacci function
	/// where result is within nativeUInt
	// You can not name it fibonacciDomain,
	// since the Fibonacci function itself
	// is defined for all whole numbers
	// but the result beyond F(n) exceeds high(nativeUInt).
	fibonacciLeftInverseRange =
		{$ifdef CPU64} 0..93 {$else} 0..47 {$endif};

{**
	implements Fibonacci sequence iteratively
	
	\param n the index of the Fibonacci number to calculate
	\returns the Fibonacci value at n
}
function fibonacci(const n: fibonacciLeftInverseRange): nativeUInt;
type
	/// more meaningful identifiers than simple integers
	relativePosition = (previous, current, next);
var
	/// temporary iterator variable
	i: longword;
	/// holds preceding fibonacci values
	f: array[relativePosition] of nativeUInt;
begin
	f[previous] := 0;
	f[current] := 1;
	
	// note, in Pascal for-loop-limits are inclusive
	for i := 1 to n do
	begin
		f[next] := f[previous] + f[current];
		f[previous] := f[current];
		f[current] := f[next];
	end;
	
	// assign to previous, bc f[current] = f[next] for next iteration
	fibonacci := f[previous];
end;

Frink

All of Frink's integers can be arbitrarily large.

fibonacciN[n] :=
{
   a = 0
   b = 1
   count = 0
   while count < n
   {
      [a,b] = [b, a + b]
      count = count + 1
   }
   return a
}

FRISC Assembly

To find the nth Fibonacci number, call this subroutine with n in register R0: the answer will be returned in R0 too. Contents of other registers are preserved.

FIBONACCI   PUSH   R1
            PUSH   R2
            PUSH   R3

            MOVE   0,  R1
            MOVE   1,  R2

FIB_LOOP    SUB    R0,  1, R0
            JP_Z   FIB_DONE

            MOVE   R2, R3
            ADD    R1, R2, R2
            MOVE   R3, R1

            JP     FIB_LOOP

FIB_DONE    MOVE   R2, R0

            POP    R3
            POP    R2
            POP    R1

            RET

FunL

Recursive

def
  fib( 0 ) = 0
  fib( 1 ) = 1
  fib( n ) = fib( n - 1 ) + fib( n - 2 )

Tail Recursive

def fib( n ) =
  def
    _fib( 0, prev, _ )    = prev
    _fib( 1, _,    next ) = next
    _fib( n, prev, next ) = _fib( n - 1, next, next + prev )

  _fib( n, 0, 1 )

Lazy List

val fib =
  def _fib( a, b ) = a # _fib( b, a + b )

  _fib( 0, 1 )

println( fib(10000) )
Output:
33644764876431783266621612005107543310302148460680063906564769974680081442166662368155595513633734025582065332680836159373734790483865268263040892463056431887354544369559827491606602099884183933864652731300088830269235673613135117579297437854413752130520504347701602264758318906527890855154366159582987279682987510631200575428783453215515103870818298969791613127856265033195487140214287532698187962046936097879900350962302291026368131493195275630227837628441540360584402572114334961180023091208287046088923962328835461505776583271252546093591128203925285393434620904245248929403901706233888991085841065183173360437470737908552631764325733993712871937587746897479926305837065742830161637408969178426378624212835258112820516370298089332099905707920064367426202389783111470054074998459250360633560933883831923386783056136435351892133279732908133732642652633989763922723407882928177953580570993691049175470808931841056146322338217465637321248226383092103297701648054726243842374862411453093812206564914032751086643394517512161526545361333111314042436854805106765843493523836959653428071768775328348234345557366719731392746273629108210679280784718035329131176778924659089938635459327894523777674406192240337638674004021330343297496902028328145933418826817683893072003634795623117103101291953169794607632737589253530772552375943788434504067715555779056450443016640119462580972216729758615026968443146952034614932291105970676243268515992834709891284706740862008587135016260312071903172086094081298321581077282076353186624611278245537208532365305775956430072517744315051539600905168603220349163222640885248852433158051534849622434848299380905070483482449327453732624567755879089187190803662058009594743150052402532709746995318770724376825907419939632265984147498193609285223945039707165443156421328157688908058783183404917434556270520223564846495196112460268313970975069382648706613264507665074611512677522748621598642530711298441182622661057163515069260029861704945425047491378115154139941550671256271197133252763631939606902895650288268608362241082050562430701794976171121233066073310059947366875

Iterative

def fib( n ) =
  a, b = 0, 1

  for i <- 1..n
    a, b = b, a+b

  a

Binet's Formula

import math.sqrt

def fib( n ) =
  phi = (1 + sqrt( 5 ))/2
  int( (phi^n - (-phi)^-n)/sqrt(5) + .5 )

Matrix Exponentiation

def mul( a, b ) =
  res = array( a.length(), b(0).length() )

  for i <- 0:a.length(), j <- 0:b(0).length()
    res( i, j ) = sum( a(i, k)*b(k, j) | k <- 0:b.length() )

  vector( res )

def
  pow( _, 0 ) = ((1, 0), (0, 1))
  pow( x, 1 ) = x
  pow( x, n )
    | 2|n = pow( mul(x, x), n\2 )
    | otherwise = mul(x, pow( mul(x, x), (n - 1)\2 ) )

def fib( n ) = pow( ((0, 1), (1, 1)), n )(0, 1)

for i <- 0..10
  println( fib(i) )
Output:
0
1
1
2
3
5
8
13
21
34
55

Futhark

Iterative

fun main(n: int): int =
  loop((a,b) = (0,1)) = for _i < n do
    (b, a + b)
  in a

FutureBasic

Iterative

window 1, @"Fibonacci Sequence", (0,0,480,620)

local fn Fibonacci( n as long ) as long
  static long s1
  static long s2
  long        temp
  
  if ( n < 2 )
    s1 = n
    exit fn
  else
    temp = s1 + s2
    s2 = s1
    s1 = temp
    exit fn
  end if
end fn = s1

long i
CFTimeInterval t

t = fn CACurrentMediaTime

for i = 0 to 40
  print i;@".\t";fn Fibonacci(i)
next i

print : printf @"Compute time: %.3f ms",(fn CACurrentMediaTime-t)*1000

HandleEvents

Output:

0.	0
1.	1
2.	1
3.	2
4.	3
5.	5
6.	8
7.	13
8.	21
9.	34
10.	55
11.	89
12.	144
13.	233
14.	377
15.	610
16.	987
17.	1597
18.	2584
19.	4181
20.	6765
21.	10946
22.	17711
23.	28657
24.	46368
25.	75025
26.	121393
27.	196418
28.	317811
29.	514229
30.	832040
31.	1346269
32.	2178309
33.	3524578
34.	5702887
35.	9227465
36.	14930352
37.	24157817
38.	39088169
39.	63245986
40.	102334155

Compute time: 2.143 ms

Recursive

Cost is a time penalty

local fn Fibonacci( n as NSInteger ) as NSInteger
NSInteger result
if n < 2 then result = n : exit fn
result = fn Fibonacci( n-1 ) + fn Fibonacci( n-2 )
end fn = result

window 1

NSInteger i
CFTimeInterval t

t = fn CACurrentMediaTime
for i = 0 to 40
print i;@".\t";fn Fibonacci(i)
next
print : printf @"Compute time: %.3f ms",(fn CACurrentMediaTime-t)*1000

HandleEvents
Output:
0.	0
1.	1
2.	1
3.	2
4.	3
5.	5
6.	8
7.	13
8.	21
9.	34
10.	55
11.	89
12.	144
13.	233
14.	377
15.	610
16.	987
17.	1597
18.	2584
19.	4181
20.	6765
21.	10946
22.	17711
23.	28657
24.	46368
25.	75025
26.	121393
27.	196418
28.	317811
29.	514229
30.	832040
31.	1346269
32.	2178309
33.	3524578
34.	5702887
35.	9227465
36.	14930352
37.	24157817
38.	39088169
39.	63245986
40.	102334155

Compute time: 2844.217 ms

Fōrmulæ

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 —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.

Programs in Fōrmulæ are created/edited online in its website.

In this page you can see and run the program(s) related to this task and their results. You can also change either the programs or the parameters they are called with, for experimentation, but remember that these programs were created with the main purpose of showing a clear solution of the task, and they generally lack any kind of validation.

Recursive

Recursive version is slow, it is O(2n), or of exponential order.

It is because it makes a lot of recursive calls.

To illustrate this, the following is a functions that makes a tree or the recursive calls:

Iterative (3 variables)

It is O(n), or of linear order.

Iterative (2 variables)

It is O(n), or of linear order.

Iterative, using a list

It is O(n), or of linear order.

Using matrix multiplication

Divide and conquer

It is an optimized version of the matrix multiplication algorithm, with an order of O(lg(n))

Closed-form

It has an order of O(lg(n))

GAP

fib := function(n)
  local a;
  a := [[0, 1], [1, 1]]^n;
  return a[1][2];
end;

GAP has also a buit-in function for that.

Fibonacci(n);

Gecho

0 1 dup wover + dup wover + dup wover + dup wover +

Prints the first several fibonacci numbers...

GML

///fibonacci(n)
//Returns the nth fibonacci number

var n, numb;
n = argument0;

if (n == 0)
    {
    numb = 0;
    }
else
    {
    var fm2, fm1;
    fm2 = 0;
    fm1 = 1;
    numb = 1;
    repeat(n-1)
        {
        numb = fm2+fm1;
        fm2 = fm1;
        fm1 = numb;
        }
    }

return numb;

Go

Recursive

func fib(a int) int {
  if a < 2 {
    return a
  }
  return fib(a - 1) + fib(a - 2)
}

Iterative

import (
	"math/big"
)

func fib(n uint64) *big.Int {
	if n < 2 {
		return big.NewInt(int64(n))
	}
	a, b := big.NewInt(0), big.NewInt(1)
	for n--; n > 0; n-- {
		a.Add(a, b)
		a, b = b, a
	}
	return b
}

Iterative using a closure

func fibNumber() func() int {
	fib1, fib2 := 0, 1
	return func() int {
		fib1, fib2 = fib2, fib1 + fib2
		return fib1
	}
}

func fibSequence(n int) int {
	f := fibNumber()
	fib := 0
	for i := 0; i < n; i++ {
		fib = f()
	}
	return fib
}

Using a goroutine and channel

func fib(c chan int) {
	a, b := 0, 1
	for {
		c <- a
		a, b = b, a+b
	}
}

func main() {
	c := make(chan int)
	go fib(c)
	for i := 0; i < 10; i++ {
		fmt.Println(<-c)
	}
}

Grain

Recursive

import String from "string"
import File from "sys/file"
let rec fib = n => if (n < 2) {
  n
} else {
  fib(n - 1) + fib(n - 2)
}
for (let mut i = 0; i <= 20; i += 1) {
  File.fdWrite(File.stdout, Pervasives.toString(fib(i)))
  ignore(File.fdWrite(File.stdout, " "))
}

Iterative

import File from "sys/file"
let fib = j => {
  let mut fnow = 0, fnext = 1
  for (let mut n = 0; n <= j; n += 1) {
    if (n == 0 || n == 1) {
      let output1 = " " ++ toString(n)
      ignore(File.fdWrite(File.stdout, output1))
    } else {
      let tempf = fnow + fnext
      fnow = fnext
      fnext = tempf
      let output2 = " " ++ toString(fnext)
      ignore(File.fdWrite(File.stdout, output2))
    }
  }
}
fib(20)
Output:

Iterative with Buffer

import Buffer from "buffer"
import String from "string"
let fib = j => {
  // set-up minimal, growable buffer
  let buf = Buffer.make(j * 2)
  let mut fnow = 0, fnext = 1
  for (let mut n = 0; n <= j; n += 1) {
    if (n == 0 || n == 1) {
      Buffer.addChar(' ', buf)
      Buffer.addString(toString(n), buf)
    } else {
      let tempf = fnow + fnext
      fnow = fnext
      fnext = tempf
      Buffer.addChar(' ', buf)
      Buffer.addString(toString(fnext), buf)
    }
  }
  // stringify buffer and return
  Buffer.toString(buf)
}
let output = fib(20)
print(output)
Output:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765

Groovy

Full "extra credit" solutions.

Recursive

A recursive closure must be pre-declared.

def rFib
rFib = { 
    it == 0   ? 0 
    : it == 1 ? 1 
    : it > 1  ? rFib(it-1) + rFib(it-2)
    /*it < 0*/: rFib(it+2) - rFib(it+1)
    
}

Iterative

def iFib = { 
    it == 0   ? 0 
    : it == 1 ? 1 
    : it > 1  ? (2..it).inject([0,1]){i, j -> [i[1], i[0]+i[1]]}[1]
    /*it < 0*/: (-1..it).inject([0,1]){i, j -> [i[1]-i[0], i[0]]}[0]
}

Analytic

final φ = (1 + 5**(1/2))/2
def aFib = { (φ**it - (-φ)**(-it))/(5**(1/2)) as BigInteger }

Test program:

def time = { Closure c ->
    def start = System.currentTimeMillis()
    def result = c()
    def elapsedMS = (System.currentTimeMillis() - start)/1000
    printf '(%6.4fs elapsed)', elapsedMS
    result
}

print "  F(n)      elapsed time   "; (-10..10).each { printf ' %3d', it }; println()
print "--------- -----------------"; (-10..10).each { print ' ---' }; println()
[recursive:rFib, iterative:iFib, analytic:aFib].each { name, fib ->
    printf "%9s ", name
    def fibList = time { (-10..10).collect {fib(it)} }
    fibList.each { printf ' %3d', it }
    println()
}
Output:
  F(n)      elapsed time    -10  -9  -8  -7  -6  -5  -4  -3  -2  -1   0   1   2   3   4   5   6   7   8   9  10
--------- ----------------- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
recursive (0.0080s elapsed) -55  34 -21  13  -8   5  -3   2  -1   1   0   1   1   2   3   5   8  13  21  34  55
iterative (0.0040s elapsed) -55  34 -21  13  -8   5  -3   2  -1   1   0   1   1   2   3   5   8  13  21  34  55
 analytic (0.0030s elapsed) -55  34 -21  13  -8   5  -3   2  -1   1   0   1   1   2   3   5   8  13  21  34  55

Harbour

Recursive

#include "harbour.ch"
Function fibb(a,b,n)
return(if(--n>0,fibb(b,a+b,n),a))

Iterative

#include "harbour.ch"
Function fibb(n) 
	local fnow:=0, fnext:=1, tempf
	while (--n>0)
		tempf:=fnow+fnext
		fnow:=fnext
		fnext:=tempf
	end while
return(fnext)

Haskell

Analytic

Works with: exact-real version 0.12.5.1

Using Binet's formula and exact real arithmetic library we can calculate arbitrary Fibonacci number exactly.

import Data.CReal

phi = (1 + sqrt 5) / 2

fib :: (Integral b) => b -> CReal 0
fib n = (phi^^n - (-phi)^^(-n))/sqrt 5

Let's try it for large numbers:

λ> fib 10 :: CReal 0
55
(0.01 secs, 137,576 bytes)
λ> fib 100 :: CReal 0
354224848179261915075
(0.01 secs, 253,152 bytes)
λ> fib 10000 :: CReal 0
33644764876431783266621612005107543310302148460680063906564769974680081442166662368155595513633734025582065332680836159373734790483865268263040892463056431887354544369559827491606602099884183933864652731300088830269235673613135117579297437854413752130520504347701602264758318906527890855154366159582987279682987510631200575428783453215515103870818298969791613127856265033195487140214287532698187962046936097879900350962302291026368131493195275630227837628441540360584402572114334961180023091208287046088923962328835461505776583271252546093591128203925285393434620904245248929403901706233888991085841065183173360437470737908552631764325733993712871937587746897479926305837065742830161637408969178426378624212835258112820516370298089332099905707920064367426202389783111470054074998459250360633560933883831923386783056136435351892133279732908133732642652633989763922723407882928177953580570993691049175470808931841056146322338217465637321248226383092103297701648054726243842374862411453093812206564914032751086643394517512161526545361333111314042436854805106765843493523836959653428071768775328348234345557366719731392746273629108210679280784718035329131176778924659089938635459327894523777674406192240337638674004021330343297496902028328145933418826817683893072003634795623117103101291953169794607632737589253530772552375943788434504067715555779056450443016640119462580972216729758615026968443146952034614932291105970676243268515992834709891284706740862008587135016260312071903172086094081298321581077282076353186624611278245537208532365305775956430072517744315051539600905168603220349163222640885248852433158051534849622434848299380905070483482449327453732624567755879089187190803662058009594743150052402532709746995318770724376825907419939632265984147498193609285223945039707165443156421328157688908058783183404917434556270520223564846495196112460268313970975069382648706613264507665074611512677522748621598642530711298441182622661057163515069260029861704945425047491378115154139941550671256271197133252763631939606902895650288268608362241082050562430701794976171121233066073310059947366875
(0.02 secs, 4,847,128 bytes)
λ> fib (-10) :: CReal 0
-55
(0.01 secs, 138,408 bytes)

Recursive

Simple definition, very inefficient.

fib x =
  if x < 1
    then 0
    else if x < 2
           then 1
           else fib (x - 1) + fib (x - 2)

Recursive with Memoization

Very fast.

fib x =
  if x < 1
    then 0
    else if x == 1
           then 1
           else fibs !! (x - 1) + fibs !! (x - 2)
  where
    fibs = map fib [0 ..]

Recursive with Memoization using memoized library

Even faster and simpler is to use a defined memoizer (e.g. from MemoTrie package):

import Data.MemoTrie
fib :: Integer -> Integer
fib = memo f where
   f 0 = 0
   f 1 = 1
   f n = fib (n-1) + fib (n-2)

You can rewrite this without introducing f explicitly

import Data.MemoTrie
fib :: Integer -> Integer
fib = memo $ \x -> case x of
   0 -> 0
   1 -> 1
   n -> fib (n-1) + fib (n-2)

Or using LambdaCase extension you can write it even shorter:

{-# Language LambdaCase #-}
import Data.MemoTrie
fib :: Integer -> Integer
fib = memo $ \case 
   0 -> 0
   1 -> 1
   n -> fib (n-1) + fib (n-2)

The version that supports negative numbers:

{-# Language LambdaCase #-}
import Data.MemoTrie
fib :: Integer -> Integer
fib = memo $ \case 
   0 -> 0
   1 -> 1
   n | n>0 -> fib (n-1) + fib (n-2)
     | otherwise -> fib (n+2) - fib (n+1)

Iterative

fib n = go n 0 1
  where
    go n a b
      | n == 0 = a
      | otherwise = go (n - 1) b (a + b)

With lazy lists

This is a standard example how to use lazy lists. Here's the (infinite) list of all Fibonacci numbers:

fib = 0 : 1 : zipWith (+) fib (tail fib)

Or alternatively:

fib = 0 : 1 : (zipWith (+) <*> tail) fib

The nth Fibonacci number is then just fib !! n. The above is equivalent to

fib = 0 : 1 : next fib where next (a: t@(b:_)) = (a+b) : next t

Also

fib = 0 : scanl (+) 1 fib

As a fold

Accumulator holds last two members of the series:

import Data.List (foldl') --'

fib :: Integer -> Integer
fib n =
  fst $
  foldl' --'
    (\(a, b) _ -> (b, a + b))
    (0, 1)
    [1 .. n]

With matrix exponentiation

Adapting the (rather slow) code from Matrix exponentiation operator, we can simply write:

import Data.List (transpose)

fib
  :: (Integral b, Num a)
  => b -> a
fib 0 = 0 -- this line is necessary because "something ^ 0" returns "fromInteger 1", which unfortunately
-- in our case is not our multiplicative identity (the identity matrix) but just a 1x1 matrix of 1
fib n = (last . head . unMat) (Mat [[1, 1], [1, 0]] ^ n)

-- Code adapted from Matrix exponentiation operator task ---------------------
(<+>)
  :: Num c
  => [c] -> [c] -> [c]
(<+>) = zipWith (+)

(<*>)
  :: Num a
  => [a] -> [a] -> a
(<*>) = (sum .) . zipWith (*)

newtype Mat a = Mat
  { unMat :: [[a]]
  } deriving (Eq)

instance Show a =>
         Show (Mat a) where
  show xm = "Mat " ++ show (unMat xm)

instance Num a =>
         Num (Mat a) where
  negate xm = Mat $ map (map negate) $ unMat xm
  xm + ym = Mat $ zipWith (<+>) (unMat xm) (unMat ym)
  xm * ym =
    Mat
      [ [ xs Main.<*> ys -- to distinguish from standard applicative operator
        | ys <- transpose $ unMat ym ]
      | xs <- unMat xm ]
  fromInteger n = Mat [[fromInteger n]]
  abs = undefined
  signum = undefined

-- TEST ----------------------------------------------------------------------
main :: IO ()
main = (print . take 10 . show . fib) (10 ^ 5)

So, for example, the hundred-thousandth Fibonacci number starts with the digits:

Output:
"2597406934"

With recurrence relations

Using Fib[m=3n+r] recurrence identities:

import Control.Arrow ((&&&))

fibstep :: (Integer, Integer) -> (Integer, Integer)
fibstep (a, b) = (b, a + b)

fibnums :: [Integer]
fibnums = map fst $ iterate fibstep (0, 1)

fibN2 :: Integer -> (Integer, Integer)
fibN2 m
  | m < 10 = iterate fibstep (0, 1) !! fromIntegral m
fibN2 m = fibN2_next (n, r) (fibN2 n)
  where
    (n, r) = quotRem m 3

fibN2_next (n, r) (f, g)
  | r == 0 = (a, b) -- 3n  ,3n+1
  | r == 1 = (b, c) -- 3n+1,3n+2
  | r == 2 = (c, d) -- 3n+2,3n+3   (*)
  where
    a =
      5 * f ^ 3 +
      if even n
        then 3 * f
        else (-3 * f) -- 3n
    b = g ^ 3 + 3 * g * f ^ 2 - f ^ 3 -- 3n+1
    c = g ^ 3 + 3 * g ^ 2 * f + f ^ 3 -- 3n+2
    d =
      5 * g ^ 3 +
      if even n
        then (-3 * g)
        else 3 * g -- 3(n+1)   (*)

main :: IO ()
main = print $ (length &&& take 20) . show . fst $ fibN2 (10 ^ 2)
Output:
(21,"35422484817926191507")

(fibN2 n) directly calculates a pair (f,g) of two consecutive Fibonacci numbers, (Fib[n], Fib[n+1]), from recursively calculated such pair at about n/3:

 *Main> (length &&& take 20) . show . fst $ fibN2 (10^6)
(208988,"19532821287077577316")

The above should take less than 0.1s to calculate on a modern box.

Other identities that could also be used are here. In particular, for (n-1,n) ---> (2n-1,2n) transition which is equivalent to the matrix exponentiation scheme, we have

f (n,(a,b)) = (2*n,(a*a+b*b,2*a*b+b*b))     -- iterate f (1,(0,1)) ; b is nth

and for (n,n+1) ---> (2n,2n+1) (derived from d'Ocagne's identity, for example),

g (n,(a,b)) = (2*n,(2*a*b-a*a,a*a+b*b))     -- iterate g (1,(1,1)) ; a is nth

Haxe

Iterative

static function fib(steps:Int, handler:Int->Void)
{
	var current = 0;
	var next = 1;
		
	for (i in 1...steps)
	{
		handler(current);

		var temp = current + next;
		current = next;
		next = temp;
	}
	handler(current);
}

As Iterator

class FibIter
{
	private var current = 0;
	private var nextItem = 1;
	private var limit:Int;
	
	public function new(limit) this.limit = limit;

	public function hasNext() return limit > 0;
	
	public function next() {
		limit--;
		var ret = current;
		var temp = current + nextItem;
		current = nextItem;
		nextItem = temp;
		return ret;
	}
}

Used like:

for (i in new FibIter(10))
	Sys.println(i);

HicEst

REAL :: Fibonacci(10)

Fibonacci = ($==2) + Fibonacci($-1) + Fibonacci($-2)
WRITE(ClipBoard) Fibonacci ! 0 1 1 2 3 5 8 13 21 34

Hoon

|=  n=@ud
=/  a=@ud  0
=/  b=@ud  1
|-
?:  =(n 0)  a
$(a b, b (add a b), n (dec n))

Hope

Recursive

dec f : num -> num;
--- f 0 <= 0;
--- f 1 <= 1;
--- f(n+2) <= f n + f(n+1);

Tail-recursive

dec fib : num -> num;
--- fib n <= l (1, 0, n)
    whererec l == \(a,b,succ c) => if c<1 then a else l((a+b),a,c)
                  |(a,b,0) => 0;

With lazy lists

This language, being one of Haskell's ancestors, also has lazy lists. Here's the (infinite) list of all Fibonacci numbers:

dec fibs : list num;
--- fibs <= fs whererec fs == 0::1::map (+) (tail fs||fs);

The nth Fibonacci number is then just fibs @ n.

Hy

Recursive implementation.

(defn fib [n]
    (if (< n 2)
        n
        (+ (fib (- n 2)) (fib (- n 1)))))

Icon and Unicon

Icon has built-in support for big numbers. First, a simple recursive solution augmented by caching for non-negative input. This examples computes fib(1000) if there is no integer argument.

procedure main(args)
    write(fib(integer(!args) | 1000)
end

procedure fib(n)
    static fCache
    initial {
        fCache := table()
        fCache[0] := 0
        fCache[1] := 1
        }
    /fCache[n] := fib(n-1) + fib(n-2)
    return fCache[n]
end

The above solution is similar to the one provided fib in memrfncs

Now, an O(logN) solution. For large N, it takes far longer to convert the result to a string for output than to do the actual computation. This example computes fib(1000000) if there is no integer argument.

procedure main(args)
    write(fib(integer(!args) | 1000000))
end

procedure fib(n)
    return fibMat(n)[1]
end

procedure fibMat(n)
    if n <= 0 then return [0,0]
    if n  = 1 then return [1,0]
    fp := fibMat(n/2)
    c := fp[1]*fp[1] + fp[2]*fp[2]
    d := fp[1]*(fp[1]+2*fp[2])
    if n%2 = 1 then return [c+d, d]
    else return [d, c]
end

IDL

Recursive

function fib,n
   if n lt 3 then return,1L else return, fib(n-1)+fib(n-2)
end

Execution time O(2^n) until memory is exhausted and your machine starts swapping. Around fib(35) on a 2GB Core2Duo.

Iterative

function fib,n
  psum = (csum = 1uL)
  if n lt 3 then return,csum
  for i = 3,n do begin
    nsum = psum + csum
    psum = csum
    csum = nsum
  endfor
  return,nsum
end

Execution time O(n). Limited by size of uLong to fib(49)

Analytic

function fib,n
  q=1/( p=(1+sqrt(5))/2 ) 
  return,round((p^n+q^n)/sqrt(5))
end

Execution time O(1), only limited by the range of LongInts to fib(48).

Idris

Analytic

fibAnalytic : Nat -> Double
fibAnalytic n = 
    floor $ ((pow goldenRatio n) - (pow (-1.0/goldenRatio) n))  / sqrt(5)
  where goldenRatio : Double 
        goldenRatio = (1.0 + sqrt(5)) / 2.0

Recursive

fibRecursive : Nat -> Nat
fibRecursive Z = Z
fibRecursive (S Z) = (S Z)
fibRecursive (S (S n)) = fibRecursive (S n) + fibRecursive n

Iterative

fibIterative : Nat -> Nat
fibIterative n = fibIterative' n Z (S Z)
  where fibIterative' : Nat -> Nat -> Nat -> Nat
        fibIterative' Z a _ = a
        fibIterative' (S n) a b = fibIterative' n b (a + b)

Lazy

fibLazy : Lazy (List Nat)
fibLazy = 0 :: 1 :: zipWith (+) fibLazy (
              case fibLazy of
                (x::xs) => xs
                [] => [])

J

The Fibonacci Sequence essay on the J Wiki presents a number of different ways of obtaining the nth Fibonacci number.

This implementation is doubly recursive except that results are cached across function calls:

fibN=: (-&2 +&$: <:)^:(1&<) M."0

Iteration:

fibN=: [: {."1 +/\@|.@]^:[&0 1

Examples:

   fibN 12
144
   fibN  i.31
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040

Java

Iterative

public static long itFibN(int n)
{
 if (n < 2)
  return n;
 long ans = 0;
 long n1 = 0;
 long n2 = 1;
 for(n--; n > 0; n--)
 {
  ans = n1 + n2;
  n1 = n2;
  n2 = ans;
 }
 return ans;
}
/**
 * O(log(n))
 */
public static long fib(long n) {
    if (n <= 0)
	return 0;

    long i = (int) (n - 1);
    long a = 1, b = 0, c = 0, d = 1, tmp1,tmp2;

    while (i > 0) {
	if (i % 2 != 0) {
            tmp1 = d * b + c * a;
	    tmp2 = d * (b + a) + c * b;
	    a = tmp1;
	    b = tmp2;
	}

        tmp1 = (long) (Math.pow(c, 2) + Math.pow(d, 2));
        tmp2 = d * (2 * c + d);
			
        c = tmp1;
        d = tmp2;

        i = i / 2;
    }
    return a + b;
}

Recursive

public static long recFibN(final int n)
{
 return (n < 2) ? n : recFibN(n - 1) + recFibN(n - 2);
}

Caching-recursive

A variant on recursive, that caches previous results, reducing complexity from O(n2) to simply O(n). Leveraging Java’s Map.computeIfAbsent makes this thread-safe, and the implementation pretty trivial.

public class Fibonacci {

    static final Map<Integer, Long> cache = new HashMap<>();
    static {
        cache.put(1, 1L);
        cache.put(2, 1L);
    }

    public static long get(int n)
    {
        return (n < 2) ? n : impl(n);
    }
    
    private static long impl(int n)
    {
        return cache.computeIfAbsent(n, k -> impl(k-1) + impl(k-2));
    }
}

Analytic

This method works up to the 92nd Fibonacci number. After that, it goes out of range.

public static long anFibN(final long n)
{
 double p = (1 + Math.sqrt(5)) / 2;
 double q = 1 / p;
 return (long) ((Math.pow(p, n) + Math.pow(q, n)) / Math.sqrt(5));
}

Tail-recursive

public static long fibTailRec(final int n)
{
 return fibInner(0, 1, n);
}

private static long fibInner(final long a, final long b, final int n)
{
 return n < 1 ? a : n == 1 ?  b : fibInner(b, a + b, n - 1);
}

Streams

import java.util.function.LongUnaryOperator;
import java.util.stream.LongStream;

public class FibUtil {
 public static LongStream fibStream() {
  return LongStream.iterate( 1l, new LongUnaryOperator() {
   private long lastFib = 0;
   @Override public long applyAsLong( long operand ) {
    long ret = operand + lastFib;
    lastFib = operand;
    return ret;
   }
  });
 }
 public static long fib(long n) {
  return fibStream().limit( n ).reduce((prev, last) -> last).getAsLong();
 }
}

JavaScript

ES5

Recursive

Basic recursive function:

function fib(n) {
  return n<2?n:fib(n-1)+fib(n-2);
}

Can be rewritten as:

function fib(n) {
 if (n<2) { return n; } else { return fib(n-1)+fib(n-2); }
}

One possibility familiar to Scheme programmers is to define an internal function for iteration through anonymous tail recursion:

function fib(n) {
  return function(n,a,b) {
    return n>0 ? arguments.callee(n-1,b,a+b) : a;
  }(n,0,1);
}

Iterative

function fib(n) {
  var a = 0, b = 1, t;
  while (n-- > 0) {
    t = a;
    a = b;
    b += t;
    console.log(a);
  }
  return a;
}

Memoization

With the keys of a dictionary,

var fib = (function(cache){
    return cache = cache || {}, function(n){
        if (cache[n]) return cache[n];
        else return cache[n] = n == 0 ? 0 : n < 0 ? -fib(-n)
            : n <= 2 ? 1 : fib(n-2) + fib(n-1);
    };
})();

with the indices of an array,

(function () {
    'use strict';

    function fib(n) {
        return Array.apply(null, Array(n + 1))
            .map(function (_, i, lst) {
                return lst[i] = (
                    i ? i < 2 ? 1 :
                    lst[i - 2] + lst[i - 1] :
                    0
                );
            })[n];
    }

    return fib(32);

})();


Output:
2178309

Y-Combinator

function Y(dn) {
    return (function(fn) {
        return fn(fn);
    }(function(fn) {
        return dn(function() {
            return fn(fn).apply(null, arguments);
        });
    }));
}
var fib = Y(function(fn) {
    return function(n) {
        if (n === 0 || n === 1) {
            return n;
        }
        return fn(n - 1) + fn(n - 2);
    };
});

Generators

function* fibonacciGenerator() {
    var prev = 0;
    var curr = 1;
    while (true) {
        yield curr;
        curr = curr + prev;
        prev = curr - prev;
    }
}
var fib = fibonacciGenerator();

ES6

Memoized

If we want access to the whole preceding series, as well as a memoized route to a particular member, we can use an accumulating fold.

(() => {
    'use strict';

    // Nth member of fibonacci series

    // fib :: Int -> Int
    function fib(n) {
        return mapAccumL(([a, b]) => [
            [b, a + b], b
        ], [0, 1], range(1, n))[0][0];
    };

    // GENERIC FUNCTIONS

    // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
    let mapAccumL = (f, acc, xs) => {
        return xs.reduce((a, x) => {
            let pair = f(a[0], x);

            return [pair[0], a[1].concat(pair[1])];
        }, [acc, []]);
    }

    // range :: Int -> Int -> Maybe Int -> [Int]
    let range = (m, n) =>
        Array.from({
            length: Math.floor(n - m) + 1
        }, (_, i) => m + i);


    // TEST
    return fib(32);

    // --> 2178309
})();

Otherwise, a simple fold will suffice.

Translation of: Haskell

(Memoized fold example)

(() => {
    'use strict';

    // fib :: Int -> Int
    let fib = n => range(1, n)
        .reduce(([a, b]) => [b, a + b], [0, 1])[0];


    // GENERIC [m..n]

    // range :: Int -> Int -> [Int]
    let range = (m, n) =>
        Array.from({
            length: Math.floor(n - m) + 1
        }, (_, i) => m + i);


    // TEST
    return fib(32);

    // --> 2178309
})();
Output:
2178309

Joy

Recursive

DEFINE fib == [small] [] [pred dup pred] [+] binrec.

Iterative

DEFINE fib == [1 0] dip [swap [+] unary] times popd.

jq

Works with: jq

Works with gojq, the Go implementation of jq

The C implementation of jq does not (yet) have infinite-precision integer arithmetic, and so using it, the following algorithms only give exact answers up to fib(78). By contrast, using the Go implementation of jq and the definition of nth_fib given below:

nth_fib(pow(2;20)) | tostring | [length, .[:10], .[-10:]]

yields

[219140,"1186800606","0691163707"]

in about 20 seconds on a 3GHz machine.

Using either the C or Go implementations, at a certain point, integers are converted to floats, but floating point precision for fib(n) fails after n = 1476: in jq, fib(1476) evaluates to 1.3069892237633987e+308

Recursive

def nth_fib_naive(n):
  if (n < 2) then n
  else nth_fib_naive(n - 1) + nth_fib_naive(n - 2)
  end;

Tail Recursive

Recent versions of jq (after July 1, 2014) include basic optimizations for tail recursion, and nth_fib is defined here to take advantage of TCO. For example, nth_fib(10000000) completes with only 380KB (that's K) of memory. However nth_fib can also be used with earlier versions of jq.

def nth_fib(n):
  # input: [f(i-2), f(i-1), countdown]
  def fib: (.[0] + .[1]) as $sum
    | .[2] as $n
    | if ($n <= 0) then $sum
      else [ .[1], $sum, $n - 1 ]
    | fib end;
  [-1, 1, n] | fib;

Example:

(range(0;5), 50) | [., nth_fib(.)]

yields:

[0,0]
[1,1]
[2,1]
[3,2]
[4,3]
[50,12586269025]

Binet's Formula

def fib_binet(n):
  (5|sqrt) as $rt
  | ((1 + $rt)/2) as $phi
  | (($phi | log) * n | exp) as $phin
  | (if 0 == (n % 2) then 1 else -1 end) as $sign
  | ( ($phin - ($sign / $phin) ) / $rt ) + .5
  | floor;

Generator

The following is a jq generator which produces the first n terms of the Fibonacci sequence efficiently, one by one. Notice that it is simply a variant of the above tail-recursive function. The function is in effect turned into a generator by changing "( _ | fib )" to "$sum, (_ | fib)".

# Generator
def fibonacci(n):
  # input: [f(i-2), f(i-1), countdown]
  def fib: (.[0] + .[1]) as $sum
           | if .[2] == 0 then $sum
             else $sum, ([ .[1], $sum, .[2] - 1 ] | fib)
             end;
  [-1, 1, n] | fib;

Julia

Recursive

fib(n) = n < 2 ? n : fib(n-1) + fib(n-2)

Iterative

function fib(n)
  x,y = (0,1)
  for i = 1:n x,y = (y, x+y) end
  x
end

Matrix form

fib(n) = ([1 1 ; 1 0]^n)[1,2]

K

Works with: Kona

Recursive

{:[x<3;1;_f[x-1]+_f[x-2]]}

Recursive with memoization

Using a (global) dictionary c.

{c::.();{v:c[a:`$$x];:[x<3;1;:[_n~v;c[a]:_f[x-1]+_f[x-2];v]]}x}

Analytic

phi:(1+_sqrt(5))%2
{_((phi^x)-((1-phi)^x))%_sqrt[5]}

Sequence to n

Works with: Kona
Works with: ngn/k
{(x(|+\)\1 1)[;1]}
{x{x,+/-2#x}/!2}

Kabap

Sequence to n

// Calculate the $n'th Fibonacci number

// Set this to how many in the sequence to generate
$n = 10;

// These are what hold the current calculation
$a = 0;
$b = 1;

// This holds the complete sequence that is generated
$sequence = "";

// Prepare a loop
$i = 0;
:calcnextnumber;
	$i = $i++;

	// Do the calculation for this loop iteration
	$b = $a + $b;
	$a = $b - $a;

	// Add the result to the sequence
	$sequence = $sequence << $a;

	// Make the loop run a fixed number of times
	if $i < $n; {
		$sequence = $sequence << ", ";
		goto calcnextnumber;
	}

// Use the loop counter as the placeholder
$i--;

// Return the sequence
return = "Fibonacci number " << $i << " is " << $a << " (" << $sequence << ")";

Klingphix

:Fibonacci
    dup 0 less
    ( ["Invalid argument"]
      [1 1 rot 2 sub [drop over over add] for]
    ) if
;

30 Fibonacci pstack print nl

msec print nl
"bertlham " input

Kotlin

enum class Fibonacci {
    ITERATIVE {
        override fun get(n: Int): Long = if (n < 2) {
            n.toLong()
        } else {
            var n1 = 0L
            var n2 = 1L
            repeat(n) {
                val sum = n1 + n2
                n1 = n2
                n2 = sum
            }
            n1
        }
    },
    RECURSIVE {
        override fun get(n: Int): Long = if (n < 2) n.toLong() else this[n - 1] + this[n - 2]
    },
    CACHING {
        val cache: MutableMap<Int, Long> = mutableMapOf(0 to 0L, 1 to 1L)
        override fun get(n: Int): Long = if (n < 2) n.toLong() else impl(n)
        private fun impl(n: Int): Long = cache.computeIfAbsent(n) { impl(it-1) + impl(it-2) }
    },
    ;
 
    abstract operator fun get(n: Int): Long
}
 
fun main() {
    val r = 0..30
    for (fib in Fibonacci.values()) {
        print("${fib.name.padEnd(10)}:")
        for (i in r) { print(" " + fib[i]) }
        println()
    }
}
Output:
ITERATIVE:  0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040
RECURSIVE:  0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040
CACHING   : 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040

L++

(defn int fib (int n) (return (? (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))))
(main (prn (fib 30)))

LabVIEW

This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.

Lambdatalk

1) basic version 
{def fib1 
 {lambda {:n}
  {if {< :n 3}
   then 1
   else {+ {fib1 {- :n 1}} {fib1 {- :n 2}}} }}}

{fib1 16} -> 987   (CPU ~ 16ms)
{fib1 30} = 832040 (CPU > 12000ms)

2) tail-recursive version
{def fib2
 {def fib2.r 
  {lambda {:a :b :i}
   {if {< :i 1} 
    then :a 
    else {fib2.r :b {+ :a :b} {- :i 1}} }}}
 {lambda {:n} {fib2.r 0 1 :n}}}

{fib2 16} -> 987    (CPU ~ 1ms)
{fib2 30} -> 832040 (CPU ~2ms)
{fib2 1000} -> 4.346655768693743e+208 (CPU ~ 22ms)  

3) Dijkstra Algorithm
{def fib3
 {def fib3.r
  {lambda {:a :b :p :q :count}
   {if {= :count 0}
    then :b
    else {if {= {% :count 2} 0}
    then {fib3.r :a :b
                {+ {* :p :p} {* :q :q}}
                {+ {* :q :q} {* 2 :p :q}}
                {/ :count 2}}
    else {fib3.r {+ {* :b :q} {* :a :q} {* :a :p}}
                {+ {* :b :p} {* :a :q}}
                :p :q
                {- :count 1}} }}}}
 {lambda {:n}
  {fib3.r 1 0 0 1 :n} }}

{fib3 16} -> 987    (CPU ~ 2ms)
{fib3 30} -> 832040 (CPU ~ 2ms)
{fib3 1000} -> 4.346655768693743e+208 (CPU ~ 3ms)  

4) memoization
{def fib4
 {def fib4.m {array.new}}    // init an empty array
 {def fib4.r {lambda {:n}
  {if {< :n 2}
   then {array.get {array.set! {fib4.m} :n 1} :n}      // init with 1,1
   else {if {equal? {array.get {fib4.m} :n} undefined} // if not exists
   then {array.get {array.set! {fib4.m} :n
                        {+ {fib4.r {- :n 1}}
                           {fib4.r {- :n 2}}}} :n}   // compute it
   else {array.get {fib4.m} :n} }}}}                   // else get it
 {lambda {:n}
  {fib4.r :n} 
  {fib4.m} }} // display the number AND all its predecessors
-> fib4
{fib4 90}  
-> 4660046610375530000 
[1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368,75025,121393,196418,
317811,514229,832040,1346269,2178309,3524578,5702887,9227465,14930352,24157817,39088169,63245986,102334155,
165580141,267914296,433494437,701408733,1134903170,1836311903,2971215073,4807526976,7778742049,12586269025,
20365011074,32951280099,53316291173,86267571272,139583862445,225851433717,365435296162,591286729879,956722026041,
1548008755920,2504730781961,4052739537881,6557470319842,10610209857723,17167680177565,27777890035288,44945570212853,
72723460248141,117669030460994,190392490709135,308061521170129,498454011879264,806515533049393,1304969544928657,
2111485077978050,3416454622906707,5527939700884757,8944394323791464,14472334024676220,23416728348467684,
37889062373143900,61305790721611580,99194853094755490,160500643816367070,259695496911122560,420196140727489660,
679891637638612200,1100087778366101900,1779979416004714000,2880067194370816000,4660046610375530000]

5) Binet's formula (non recursive)
{def fib5 
 {lambda {:n}
  {let { {:n :n} {:sqrt5 {sqrt 5}} }
   {round {/ {- {pow {/ {+ 1 :sqrt5} 2} :n} 
                {pow {/ {- 1 :sqrt5} 2} :n}} :sqrt5}}} }}

{fib5 16} -> 987    (CPU ~ 1ms) 
{fib5 30} -> 832040 (CPU ~ 1ms)
{fib5 1000} -> 4.346655768693743e+208 (CPU ~ 1ms)

Lang

Iterative

fp.fib = ($n) -> {
	if($n < 2) {
		return $n
	}
	
	$prev = 1
	$cur = 1
	$i = 2
	while($i < $n) {
		$tmp = $cur
		$cur += $prev
		$prev = $tmp
		
		$i += 1
	}
	
	return $cur
}

Recursive

fp.fib = ($n) -> {
	if($n < 2) {
		return $n
	}
	
	return parser.op(fp.fib($n - 1) + fp.fib($n - 2))
}

Lang5

[] '__A set : dip swap __A swap 2 compress collapse '__A set execute
    __A -1 extract nip ;  : nip swap drop ;  : tuck swap over ;
: -rot rot rot ; : 0= 0 == ; : 1+ 1 + ; : 1- 1 - ; : sum '+ reduce ;
: bi 'keep dip execute ;  : keep over 'execute dip ;

: fib dup 1 > if dup 1- fib swap 2 - fib + then ;
: fib  dup 1 > if "1- fib" "2 - fib" bi + then ;

langur

val .fibonacci = fn(.x) { if(.x < 2: .x ; self(.x - 1) + self(.x - 2)) }

writeln map .fibonacci, series 2..20
Output:
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]

Lasso

define fibonacci(n::integer) => {

	#n < 1 ? return false

	local(
		swap	= 0,
		n1		= 0,
		n2		= 1
	)

	loop(#n) => {
        #swap = #n1 + #n2;
        #n2 = #n1;
        #n1 = #swap;
	}
	return #n1

}

fibonacci(0) //->output false
fibonacci(1) //->output 1
fibonacci(2) //->output 1
fibonacci(3) //->output 2

Latitude

Recursive

fibo := {
  takes '[n].
  if { n <= 1. } then {
    n.
  } else {
    fibo (n - 1) + fibo (n - 2).
  }.
}.

Memoization

fibo := {
  takes '[n].
  cache := here cache.
  { cache slot? (n ordinal). } ifFalse {
    cache slot (n ordinal) =
      if { n <= 1. } then {
        n.
      } else {
        fibo (n - 1) + fibo (n - 2).
      }.
  }.
  cache slot (n ordinal).
} tap {
  ;; Attach the cache to the method object itself.
  #'self cache := Object clone.
}.


Lean

It runs on Lean 3.4.2:

-- Our first implementation is the usual recursive definition:
def fib1 : ℕ → ℕ 
| 0       := 0
| 1       := 1
| (n + 2) := fib1 n + fib1 (n + 1)


-- We can give a second more efficient implementation using an auxiliary function:
def fib_aux : ℕ → ℕ → ℕ → ℕ 
| 0 a b       := b
| (n + 1) a b := fib_aux n (a + b) a

def fib2 : ℕ → ℕ 
| n := fib_aux n 1 0


-- Use #eval to check computations:
#eval fib1 20
#eval fib2 20


It runs on Lean 4:

-- Naive version
def fib1 (n : Nat) : Nat :=
  match n with
  | 0 => 0
  | 1 => 1
  | (k + 2) => fib1 k + fib1 (k + 1)

-- More efficient version
def fib_aux (n : Nat) (a : Nat) (b : Nat) : Nat :=
  match n with
  | 0 => b
  | (k + 1) => fib_aux k (a + b) a
 
def fib2 (n : Nat) : Nat :=
  fib_aux n 1 0

-- Examples
#eval fib1 20
#eval fib2 20

LFE

Recursive

(defun fib
  ((0) 0)
  ((1) 1)
  ((n)
    (+ (fib (- n 1))
       (fib (- n 2)))))

Iterative

(defun fib
  ((n) (when (>= n 0))
    (fib n 0 1)))

(defun fib
  ((0 result _)
    result)
  ((n result next)
    (fib (- n 1) next (+ result next))))


Lingo

Recursive

on fib (n)
  if n<2 then return n
  return fib(n-1)+fib(n-2)
end

Iterative

on fib (n)
  if n<2 then return n    
  fibPrev = 0
  fib = 1
  repeat with i = 2 to n
    tmp = fib
    fib = fib + fibPrev
    fibPrev = tmp
  end repeat
  return fib
end

Analytic

on fib (n)
  sqrt5 = sqrt(5.0)
  p = (1+sqrt5)/2
  q = 1 - p
  return integer((power(p,n)-power(q,n))/sqrt5)
end

Lisaac

- fib(n : UINTEGER_32) : UINTEGER_64 <- (
  + result : UINTEGER_64;
  (n < 2).if {
    result := n;
  } else {
    result := fib(n - 1) + fib(n - 2);
  };
  result
);

LiveCode

-- Iterative, translation of the basic version.
function fibi n
    put 0 into aa
    put 1 into b
    repeat with i = 1 to n
        put aa + b into temp
        put b into aa
        put temp into b
    end repeat
    return aa
end fibi

-- Recursive
function fibr n
     if n <= 1 then
        return n
    else
        return fibr(n-1) + fibr(n-2)
    end if
end fibr

LLVM

; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.

; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps

$"PRINT_LONG" = comdat any
@"PRINT_LONG" = linkonce_odr unnamed_addr constant [5 x i8] c"%ld\0A\00", comdat, align 1

;--- The declaration for the external C printf function.
declare i32 @printf(i8*, ...)

;--------------------------------------------------------------------
;-- Function for calculating the nth fibonacci numbers
;--------------------------------------------------------------------
define i32 @fibonacci(i32) {
    %2 = alloca i32, align 4            ;-- allocate local copy of n
    %3 = alloca i32, align 4            ;-- allocate a
    %4 = alloca i32, align 4            ;-- allocate b
    store i32 %0, i32* %2, align 4      ;-- store copy of n
    store i32 0, i32* %3, align 4       ;-- a := 0
    store i32 1, i32* %4, align 4       ;-- b := 1
    br label %loop

loop:
    %5 = load i32, i32* %2, align 4     ;-- load n
    %6 = icmp sgt i32 %5, 0             ;-- n > 0
    br i1 %6, label %loop_body, label %exit

loop_body:
    %7 = load i32, i32* %3, align 4     ;-- load a
    %8 = load i32, i32* %4, align 4     ;-- load b
    %9 = add nsw i32 %7, %8             ;-- t = a + b
    store i32 %8, i32* %3, align 4      ;-- store a = b
    store i32 %9, i32* %4, align 4      ;-- store b = t
    %10 = load i32, i32* %2, align 4    ;-- load n
    %11 = add nsw i32 %10, -1           ;-- decrement n
    store i32 %11, i32* %2, align 4     ;-- store n
    br label %loop

exit:
    %12 = load i32, i32* %3, align 4    ;-- load a
    ret i32 %12                         ;-- return a
}

;--------------------------------------------------------------------
;-- Main function for printing successive fibonacci numbers
;--------------------------------------------------------------------
define i32 @main() {
    %1 = alloca i32, align 4            ;-- allocate index
    store i32 0, i32* %1, align 4       ;-- index := 0
    br label %loop

loop:
    %2 = load i32, i32* %1, align 4     ;-- load index
    %3 = icmp sle i32 %2, 12            ;-- index <= 12
    br i1 %3, label %loop_body, label %exit

loop_body:
    %4 = load i32, i32* %1, align 4     ;-- load index
    %5 = call i32 @fibonacci(i32 %4)
    %6 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"PRINT_LONG", i32 0, i32 0), i32 %5)
    %7 = load i32, i32* %1, align 4     ;-- load index
    %8 = add nsw i32 %7, 1              ;-- increment index
    store i32 %8, i32* %1, align 4      ;-- store index
    br label %loop

exit:
    ret i32 0                           ;-- return EXIT_SUCCESS
}
Output:
0
1
1
2
3
5
8
13
21
34
55
89
144

to fib "loop
make   "fib1 0
make   "fib2 1

type [You requested\ ]
type :loop
print [\ Fibonacci Numbers]
   type :fib1
   type [\  ]
   type :fib2  
   type [\  ]
   
make "loop :loop - 2
repeat :loop [ make "fibnew :fib1 + :fib2 type :fibnew type [\  ] make "fib1 :fib2 make "fib2 :fibnew ]
   print [\  ]
     
end

LOLCODE

HAI 1.2
HOW DUZ I fibonacci YR N
  EITHER OF BOTH SAEM N AN 1 AN BOTH SAEM N AN 0
  O RLY?
    YA RLY, FOUND YR 1
    NO WAI
      I HAS A N1
      I HAS A N2
      N1 R DIFF OF N AN 1
      N2 R DIFF OF N AN 2
      N1 R fibonacci N1
      N2 R fibonacci N2
      FOUND YR SUM OF N1 AN N2
  OIC
IF U SAY SO
KTHXBYE

LSL

Rez a box on the ground, and add the following as a New Script.

integer Fibonacci(integer n) {
	if(n<2) {
		return n;
	} else {
		return Fibonacci(n-1)+Fibonacci(n-2);
	}
}
default {
	state_entry() {
		integer x = 0;
		for(x=0 ; x<35 ; x++) {
			llOwnerSay("Fibonacci("+(string)x+")="+(string)Fibonacci(x));
		}
	}
}

Output:

Fibonacci(0)=0
Fibonacci(1)=1
Fibonacci(2)=1
Fibonacci(3)=2
Fibonacci(4)=3
Fibonacci(5)=5
Fibonacci(6)=8
Fibonacci(7)=13
Fibonacci(8)=21
Fibonacci(9)=34
Fibonacci(10)=55
Fibonacci(11)=89
Fibonacci(12)=144
Fibonacci(13)=233
Fibonacci(14)=377
Fibonacci(15)=610
Fibonacci(16)=987
Fibonacci(17)=1597
Fibonacci(18)=2584
Fibonacci(19)=4181
Fibonacci(20)=6765
Fibonacci(21)=10946
Fibonacci(22)=17711
Fibonacci(23)=28657
Fibonacci(24)=46368
Fibonacci(25)=75025
Fibonacci(26)=121393
Fibonacci(27)=196418
Fibonacci(28)=317811
Fibonacci(29)=514229
Fibonacci(30)=832040
Fibonacci(31)=1346269
Fibonacci(32)=2178309
Fibonacci(33)=3524578
Fibonacci(34)=5702887

Lua

Recursive

--calculates the nth fibonacci number. Breaks for negative or non-integer n.
function fibs(n) 
  return n < 2 and n or fibs(n - 1) + fibs(n - 2) 
end

Pedantic Recursive

--more pedantic version, returns 0 for non-integer n
function pfibs(n)
  if n ~= math.floor(n) then return 0
  elseif n < 0 then return pfibs(n + 2) - pfibs(n + 1)
  elseif n < 2 then return n
  else return pfibs(n - 1) + pfibs(n - 2)
  end
end

Tail Recursive

function a(n,u,s) if n<2 then return u+s end return a(n-1,u+s,u) end
function trfib(i) return a(i-1,1,0) end

Table Recursive

fib_n = setmetatable({1, 1}, {__index = function(z,n) return n<=0 and 0 or z[n-1] + z[n-2] end})

Table Recursive 2

-- table recursive done properly (values are actually saved into table;
-- also the first element of Fibonacci sequence is 0, so the initial table should be {0, 1}).
fib_n = setmetatable({0, 1}, {
  __index = function(t,n)
    if n <= 0 then return 0 end
    t[n] = t[n-1] + t[n-2]
    return t[n]
  end
})

Iterative

function ifibs(n)
  local p0,p1=0,1
  for _=1,n do p0,p1 = p1,p0+p1 end
  return p0
end

Luck

function fib(x: int): int = (
   let cache = {} in
   let fibc x = if x<=1 then x else (
      if x not in cache then
      cache[x] = fibc(x-1) + fibc(x-2);
      cache[x]
   ) in fibc(x)
);;
for x in range(10) do print(fib(x))

Lush

(de fib-rec (n)
  (if (< n 2)
      n
     (+ (fib-rec (- n 2)) (fib-rec (- n 1)))))

M2000 Interpreter

Return decimal type and use an Inventory (as closure) to store known return values. All closures are in scope in every recursive call (we use here lambda(), but we can use fib(), If we make Fib1=fib then we have to use lambda() for recursion.

Inventory K=0:=0,1:=1
fib=Lambda K (x as decimal)-> {
      If Exist(K, x) Then =Eval(K) :Exit
      Def Ret as Decimal
      Ret=If(x>1->Lambda(x-1)+Lambda(x-2), x)
      Append K, x:=Ret
      =Ret
}
\\ maximum 139
For i=1 to 139 {
      Print Fib(i)
}

Here an example where we use a BigNum class to make a Group which hold a stack of values, and take 14 digits per item in stack. We can use inventory to hold groups, so we use the fast fib() function from code above, where we remove the type definition of Ret variable, and set two first items in inventory as groups.

Class BigNum {
      a=stack
      Function Digits {
            =len(.a)*14-(14-len(str$(stackitem(.a,len(.a)) ,"")))
      }
      Operator "+" (n) {
            \\ we get a copy, but .a is pointer
             \\ we make a copy, and get a new pointer
            .a<=stack(.a)
            acc=0
            carry=0
            const d=100000000000000@
                  k=min.data(Len(.a), len(n.a))
                  i=each(.a, 1,k )
                  j=each(n.a, 1,k)
                  while  i, j {
                        acc=stackitem(i)+stackitem(j)+carry
                        carry= acc div d
                        return .a, i^+1:=acc mod d
                  } 
                  if len(.a)<len(n.a) Then  {
                        i=each(n.a, k+1, -1)
                        while i {
                              acc=stackitem(i)+carry
                              carry= acc div d
                              stack .a  {data acc mod d}
                        }
                  } ELse.if len(.a)>len(n.a) Then  {
                        i=each(.a, k+1, -1)
                        while i {
                              acc=stackitem(i)+carry
                              carry= acc div d
                              Return .a, i^+1:=acc mod d
                              if carry else exit
                        }     
                  }
                  if carry then stack .a { data carry}
      }
      Function tostring$ {
            if len(.a)=0 then ="0" : Exit
            if len(.a)=1 then =str$(Stackitem(.a),"") : Exit
            document buf$=str$(Stackitem(.a, len(.a)),"")
            for i=len(.a)-1 to  1 {
                  Stack .a {
                        buf$=str$(StackItem(i), "00000000000000")
                  }
            }
            =buf$
      }
      class:
      Module BigNum (s$) {
            s$=filter$(s$,"+-.,")
            if s$<>""  Then {
                  repeat {
                        If len(s$)<14 then Stack .a { Data  val(s$) }: Exit
                        Stack .a { Data  val(Right$(s$, 14)) }
                        S$=Left$(S$, len(S$)-14)
                  } Until S$=""
            }
      }
} 

Inventory K=0:=BigNum("0"),1:=BigNum("1")
fib=Lambda K (x as decimal)-> {
      If Exist(K, x) Then =Eval(K) :Exit
      Ret=If(x>1->Lambda(x-1)+Lambda(x-2), bignum(str$(x,"")))
      Append K, x:=Ret
      =Ret
}
\\ Using this to handle form  refresh by code
Set Fast!
For i=1 to 4000 {
      N=Fib(i)
      Print i
      Print N.tostring$()
      Refresh
}

M4

define(`fibo',`ifelse(0,$1,0,`ifelse(1,$1,1,
`eval(fibo(decr($1)) + fibo(decr(decr($1))))')')')dnl
define(`loop',`ifelse($1,$2,,`$3($1) loop(incr($1),$2,`$3')')')dnl
loop(0,15,`fibo')

MAD

            NORMAL MODE IS INTEGER
            
            INTERNAL FUNCTION(N)
            ENTRY TO FIB.
            A = 0
            B = 1
            THROUGH LOOP, FOR N=N, -1, N.E.0
            C = A + B
            A = B
LOOP        B = C
            FUNCTION RETURN A
            END OF FUNCTION
            
            THROUGH SHOW, FOR I=0, 1, I.GE.20
SHOW        PRINT FORMAT FNUM, I, FIB.(I)
            VECTOR VALUES FNUM = $4HFIB(,I2,4H) = ,I4*$
            END OF PROGRAM
Output:
FIB( 0) =    0
FIB( 1) =    1
FIB( 2) =    1
FIB( 3) =    2
FIB( 4) =    3
FIB( 5) =    5
FIB( 6) =    8
FIB( 7) =   13
FIB( 8) =   21
FIB( 9) =   34
FIB(10) =   55
FIB(11) =   89
FIB(12) =  144
FIB(13) =  233
FIB(14) =  377
FIB(15) =  610
FIB(16) =  987
FIB(17) = 1597
FIB(18) = 2584
FIB(19) = 4181


Maple

> f := n -> ifelse(n<3,1,f(n-1)+f(n-2));
> f(2);
  1
> f(3);
  2

Mathematica / Wolfram Language

The Wolfram Language already has a built-in function Fibonacci, but a simple recursive implementation would be

fib[0] = 0
fib[1] = 1
fib[n_Integer] := fib[n - 1] + fib[n - 2]

An optimization is to cache the values already calculated:

fib[0] = 0
fib[1] = 1
fib[n_Integer] := fib[n] = fib[n - 1] + fib[n - 2]

The above implementations may be too simplistic, as the first is incredibly slow for any reasonable range due to nested recursions and while the second is faster it uses an increasing amount of memory. The following uses recursion much more effectively while not using memory:

fibi[prvprv_Integer, prv_Integer, rm_Integer] :=
  If[rm < 1, prvprv, fibi[prv, prvprv + prv, rm - 1]]
fib[n_Integer] := fibi[0, 1, n]

However, the recursive approaches in Mathematica are limited by the limit set for recursion depth (default 1024 or 4096 for the above cases), limiting the range for 'n' to about 1000 or 2000. The following using an iterative approach has an extremely high limit (greater than a million):

fib[n_Integer] := Block[{tmp, prvprv = 0, prv = 1},
  For[i = 0, i < n, i++, tmp = prv; prv += prvprv; prvprv = tmp];
  Return[prvprv]]

If one wanted a list of Fibonacci numbers, the following is quite efficient:

fibi[{prvprv_Integer, prv_Integer}] := {prv, prvprv + prv}
fibList[n_Integer] := Map[Take[#, 1] &, NestList[fibi, {0, 1}, n]] // Flatten

Output from the last with "fibList[100]":

{0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, \
1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, \
196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, \
9227465, 14930352, 24157817, 39088169, 63245986, 102334155, \
165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, \
2971215073, 4807526976, 7778742049, 12586269025, 20365011074, \
32951280099, 53316291173, 86267571272, 139583862445, 225851433717, \
365435296162, 591286729879, 956722026041, 1548008755920, \
2504730781961, 4052739537881, 6557470319842, 10610209857723, \
17167680177565, 27777890035288, 44945570212853, 72723460248141, \
117669030460994, 190392490709135, 308061521170129, 498454011879264, \
806515533049393, 1304969544928657, 2111485077978050, \
3416454622906707, 5527939700884757, 8944394323791464, \
14472334024676221, 23416728348467685, 37889062373143906, \
61305790721611591, 99194853094755497, 160500643816367088, \
259695496911122585, 420196140727489673, 679891637638612258, \
1100087778366101931, 1779979416004714189, 2880067194370816120, \
4660046610375530309, 7540113804746346429, 12200160415121876738, \
19740274219868223167, 31940434634990099905, 51680708854858323072, \
83621143489848422977, 135301852344706746049, 218922995834555169026, \
354224848179261915075}

The Wolfram Language can also solve recurrence equations using the built-in function RSolve

fib[n] /. RSolve[{fib[n] == fib[n - 1] + fib[n - 2], fib[0] == 0, 
    fib[1] == 1}, fib[n], n][[1]]

which evaluates to the built-in function Fibonacci[n]

This function can also be expressed as

Fibonacci[n] // FunctionExpand // FullSimplify

which evaluates to

(2^-n ((1 + Sqrt[5])^n - (-1 + Sqrt[5])^n Cos[n π]))/Sqrt[5]

and is defined for all real or complex values of n.

MATLAB

Matrix

Translation of: Julia
function f = fib(n)
	
	f = [1 1 ; 1 0]^(n-1);
	f = f(1,1);
	
end

Iterative

function F = fibonacci(n)
    
    Fn = [1 0]; %Fn(1) is F_{n-2}, Fn(2) is F_{n-1} 
    F = 0; %F is F_{n}
    
    for i = (1:abs(n))
        Fn(2) = F;
        F = sum(Fn);
        Fn(1) = Fn(2);
    end
        
    if n < 0
        F = F*((-1)^(n+1));
    end   

end

Dramadah Matrix Method

The MATLAB help file suggests an interesting method of generating the Fibonacci numbers. Apparently the determinate of the Dramadah Matrix of type 3 (MATLAB designation) and size n-by-n is the nth Fibonacci number. This method is implimented below.

function number = fibonacci2(n)
    
    if n == 1
        number = 1;
    elseif n == 0
        number = 0;
    elseif n < 0
        number = ((-1)^(n+1))*fibonacci2(-n);;
    else
        number = det(gallery('dramadah',n,3));
    end

end

Tartaglia/Pascal Triangle Method

function number = fibonacci(n)
%construct the Tartaglia/Pascal Triangle
    pt=tril(ones(n));
    for r = 3 : n
    % Every element is the addition of the two elements
    % on top of it. That means the previous row.
        for c = 2 : r-1
            pt(r, c) = pt(r-1, c-1) + pt(r-1, c);
        end   
    end
    number=trace(rot90(pt));
end

Maxima

/* fib(n) is built-in; here is an implementation */
fib2(n) := (matrix([0, 1], [1, 1])^^n)[1, 2]$

fib2(100)-fib(100);
0

fib2(-10);
-55

MAXScript

Iterative

fn fibIter n =
(
    if n < 2 then
    (
        n
    )
    else
    (
        fib = 1
        fibPrev = 1
        for num in 3 to n do
        (
            temp = fib
            fib += fibPrev
            fibPrev = temp
        )
        fib
    ) 
)

Recursive

fn fibRec n =
(
    if n < 2 then
    (
        n
    )
    else
    (
        fibRec (n - 1) + fibRec (n - 2)
    )
)

Mercury

Mercury is both a logic language and a functional language. As such there are two possible interfaces for calculating a Fibonacci number. This code shows both styles. Note that much of the code here is ceremony put in place to have this be something which can actually compile. The actual Fibonacci number generation is contained in the predicate fib/2 and in the function fib/1. The predicate main/2 illustrates first the unification semantics of the predicate form and the function call semantics of the function form.

The provided code uses a very naive form of generating a Fibonacci number. A more realistic implementation would use memoization to cache previous results, exchanging time for space. Also, in the case of supplying both a function implementation and a predicate implementation, one of the two would be implemented in terms of the other. Examples of this are given as comments below.

fib.m

% The following code is derived from the Mercury Tutorial by Ralph Becket.
% http://www.mercury.csse.unimelb.edu.au/information/papers/book.pdf
:- module fib.
 
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
 
:- implementation.
:- import_module int.
 
:- pred fib(int::in, int::out) is det.
fib(N, X) :-
    ( if N =< 2
          then X = 1
          else fib(N - 1, A), fib(N - 2, B), X = A + B ).
 
:- func fib(int) = int is det.
fib(N) = X :- fib(N, X).
 
main(!IO) :-
    fib(40, X),
    write_string("fib(40, ", !IO),
    write_int(X, !IO),
    write_string(")\n", !IO),
 
    write_string("fib(40) = ", !IO),
    write_int(fib(40), !IO),
    write_string("\n", !IO).

Iterative algorithm

The much faster iterative algorithm can be written as:

:- pred fib_acc(int::in, int::in, int::in, int::in, int::out) is det.

fib_acc(N, Limit, Prev2, Prev1, Res) :-
    ( N < Limit ->
        % limit not reached, continue computation.
        ( N =< 2 ->
            Res0 = 1
        ;
            Res0 = Prev2 + Prev1
        ),
        fib_acc(N+1, Limit, Prev1, Res0, Res)
    ;
        % Limit reached, return the sum of the two previous results.
        Res = Prev2 + Prev1
    ).

This predicate can be called as

fib_acc(1, 40, 1, 1, Result)

It has several inputs which form the loop, the first is the current number, the second is a limit, ie when to stop counting. And the next two are accumulators for the last and next-to-last results.

Memoization

But what if you want the speed of the fib_acc with the recursive (more declarative) definition of fib? Then use memoization, because Mercury is a pure language fib(N, F) will always give the same F for the same N, guaranteed. Therefore memoization asks the compiler to use a table to remember the value for F for any N, and it's a one line change:

:- pragma memo(fib/2).
:- pred fib(int::in, int::out) is det.
fib(N, X) :-
    ( if N =< 2
          then X = 1
          else fib(N - 1, A), fib(N - 2, B), X = A + B ).

We've shown the definition of fib/2 again, but the only change here is the memoization pragma (see the reference manual). This is not part of the language specification and different Mercury implementations are allowed to ignore it, however there is only one implementation so in practice memoization is fully supported.

Memoization trades speed for space, a table of results is constructed and kept in memory. So this version of fib consumes more memory than than fib_acc. It is also slightly slower than fib_acc since it must manage its table of results but it is much much faster than without memoization. Memoization works very well for the Fibonacci sequence because in the naive version the same results are calculated over and over again.

Metafont

vardef fibo(expr n) =
if n=0: 0
elseif n=1: 1
else:
  fibo(n-1) + fibo(n-2)
fi
enddef;

for i=0 upto 10: show fibo(i); endfor
end


min

Works with: min version 0.37.0
(
  (2 <)
  (pred (1 0 (over + swap)) dip times pop)
  unless
) ^fib

MiniScript

An efficient solution (for n >= 0):

fibonacci = function(n)
    if n < 2 then return n
    n1 = 0
    n2 = 1
    for i in range(n-1, 1)
        ans = n1 + n2
        n1 = n2
        n2 = ans
    end for
    return ans
end function

print fibonacci(6)

And for comparison, a recursive solution (also for n >= 0):

rfib = function(n)
    if n < 1 then return 0
    if n == 1 then return 1
    return rfib(n-1) + rfib(n-2)
end function

print rfib(6)

MiniZinc

function var int: fibonacci(int: n) =
  let {
    array[0..n] of var int: fibonacci;
    constraint forall(a in 0..n)(
      fibonacci[a] = if (a == 0 \/ a == 1) then
        a
      else
        fibonacci[a-1]+fibonacci[a-2]
      endif
    )
  } in fibonacci[n];
 
var int: fib = fibonacci(6);
solve satisfy;
output [show(fib),"\n"];

MIPS Assembly

This is the iterative approach to the Fibonacci sequence.

	.text
main:	li	$v0, 5		# read integer from input. The read integer will be stroed in $v0
	syscall
	
	beq	$v0, 0, is1
	beq	$v0, 1,	is1	
	
	li	$s4, 1		# the counter which has to equal to $v0	
		
	li	$s0, 1
	li	$s1, 1

loop:	add	$s2, $s0, $s1
	addi	$s4, $s4, 1
	beq	$v0, $s4, iss2
	
	add	$s0, $s1, $s2
	addi	$s4, $s4, 1
	beq	$v0, $s4, iss0
	
	add	$s1, $s2, $s0
	addi	$s4, $s4, 1
	beq	$v0, $s4, iss1

	b 	loop

iss0:	move	$a0, $s0	
	b	print

iss1:	move	$a0, $s1	
	b	print

iss2:	move	$a0, $s2	
	b	print
	
	
is1:	li	$a0, 1
	b 	print
	
print:	li	$v0, 1
	syscall
	li	$v0, 10
	syscall

Mirah

def fibonacci(n:int)
    return n if n < 2
    fibPrev = 1
    fib = 1
    3.upto(Math.abs(n)) do 
        oldFib = fib
        fib = fib + fibPrev
        fibPrev = oldFib
    end
    fib * (n<0 ? int(Math.pow(n+1, -1)) : 1)
end

puts fibonacci 1
puts fibonacci 2
puts fibonacci 3
puts fibonacci 4
puts fibonacci 5
puts fibonacci 6
puts fibonacci 7

МК-61/52

П0	1	lg	Вx	<->	+	L0	03	С/П	БП
03

Instruction: n В/О С/П, where n is serial number of the number of Fibonacci sequence; С/П for the following numbers.

ML

Standard ML

Tail Recursion

This version is tail recursive.

fun fib n = 
    let
	fun fib' (0,a,b) = a
	  | fib' (n,a,b) = fib' (n-1,a+b,a)
    in
	fib' (n,0,1)
    end

Recursion

fun fib n = if n < 2 then n else fib (n - 1) + fib (n - 2)

MLite

Recursion

Tail recursive.

fun fib 
        (0, x1, x2) = x2
      | (n, x1, x2) = fib (n-1, x2, x1+x2)
      | n = fib (n, 0, 1)

ML/I

MCSKIP "WITH" NL
"" Fibonacci - recursive
MCSKIP MT,<>
MCINS %.
MCDEF FIB WITHS ()
AS <MCSET T1=%A1.
MCGO L1 UNLESS 2 GR T1
%T1.<>MCGO L0
%L1.%FIB(%T1.-1)+FIB(%T1.-2).>
fib(0) is FIB(0)
fib(1) is FIB(1)
fib(2) is FIB(2)
fib(3) is FIB(3)
fib(4) is FIB(4)
fib(5) is FIB(5)

Modula-2

MODULE Fibonacci;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;

PROCEDURE Fibonacci(n : LONGINT) : LONGINT;
VAR
    a,b,c : LONGINT;
BEGIN
    IF n<0 THEN RETURN 0 END;

    a:=1;
    b:=1;

    WHILE n>0 DO
        c := a + b;
        a := b;
        b := c;
        DEC(n)
    END;

    RETURN a
END Fibonacci;

VAR
    buf : ARRAY[0..63] OF CHAR;
    i : INTEGER;
    r : LONGINT;
BEGIN
    FOR i:=0 TO 10 DO
        r := Fibonacci(i);

        FormatString("%l\n", buf, r);
        WriteString(buf);
    END;

    ReadChar
END Fibonacci.

Modula-3

Recursive

PROCEDURE Fib(n: INTEGER): INTEGER =
  BEGIN
    IF n < 2 THEN
      RETURN n;
    ELSE
      RETURN Fib(n-1) + Fib(n-2);
    END;
  END Fib;

Iterative (with negatives)

PROCEDURE IterFib(n: INTEGER): INTEGER =

VAR

  limit := ABS(n);
  prev := 0;
  curr, next: INTEGER;

BEGIN

  (* trivial case *)
  IF n = 0 THEN RETURN 0; END;

  IF n > 0 THEN (* positive case *)

    curr := 1;
    FOR i := 2 TO limit DO
      next := prev + curr;
      prev := curr;
      curr := next;
    END;

  ELSE (* negative case *)

    curr := -1;
    FOR i := 2 TO limit DO
      next := prev - curr;
      prev := curr;
      curr := next;
    END;

  END;

  RETURN curr;

END IterFib;

Monicelli

Recursive version. It includes a main that reads a number N from standard input and prints the Nth Fibonacci number.

# Main
Lei ha clacsonato
voglio un nonnulla, Necchi mi porga un nonnulla
il nonnulla come se fosse brematurata la supercazzola bonaccia con il nonnulla o scherziamo?
un nonnulla a posterdati

# Fibonacci function 'bonaccia'
blinda la supercazzola Necchi bonaccia con antani Necchi o scherziamo? che cos'è l'antani? 
minore di 3: vaffanzum 1! o tarapia tapioco: voglio unchiamo, Necchi come se fosse brematurata 
la supercazzola bonaccia con antani meno 1 o scherziamo? voglio duechiamo, 
Necchi come se fosse brematurata la supercazzola bonaccia con antani meno 2 o scherziamo? vaffanzum 
unchiamo più duechiamo! e velocità di esecuzione

MontiLang

Reads number from standard input and prints to that number in the fibonacci sequence

0 VAR a .
1 VAR b .
INPUT TOINT
FOR :
    a b + VAR c .
    a PRINT .
    b VAR a .
    c VAR b .
ENDFOR

Forth-style solution

def over
    swap dup rot swap
enddef

|Enter a number to obtain Fibonacci sequence: | input nip var count .
0 1
FOR count
    over out |, | out . + swap
ENDFOR
. print
input
clear

Simpler

|Enter a number to obtain Fibonacci sequence: | input nip 1 - var count .
0 1
FOR count
    out |, | out . dup rot +
ENDFOR
print
input   /# wait until press ENTER #/
clear   /# empties the stack #/

MUMPS

Iterative

FIBOITER(N)
 ;Iterative version to get the Nth Fibonacci number
 ;N must be a positive integer
 ;F is the tree containing the values
 ;I is a loop variable.
 QUIT:(N\1'=N)!(N<0) "Error: "_N_" is not a positive integer."
 NEW F,I
 SET F(0)=0,F(1)=1
 QUIT:N<2 F(N)
 FOR I=2:1:N SET F(I)=F(I-1)+F(I-2)
 QUIT F(N)
USER>W $$FIBOITER^ROSETTA(30)
832040

Nanoquery

Iterative

def fibIter(n)
        if (n < 2)
                return n
        end if
 
        $fib = 1
        $fibPrev = 1
 
	for num in range(2, n - 1)
                fib += fibPrev
                fibPrev = fib - fibPrev
        end for
 
        return fib
end

Nemerle

Recursive

using System;
using System.Console;

module Fibonacci
{
    Fibonacci(x : long) : long
    {
        |x when x < 2 => x
        |_ => Fibonacci(x - 1) + Fibonacci(x - 2)
    }
    
    Main() : void
    {
        def num = Int64.Parse(ReadLine());
        foreach (n in $[0 .. num])
            WriteLine("{0}: {1}", n, Fibonacci(n));
    }
}

Tail Recursive

Fibonacci(x : long, current : long, next : long) : long
{
    match(x)
    {
        |0 => current
        |_ => Fibonacci(x - 1, next, current + next)
    }
}
  
Fibonacci(x : long) : long
{
    Fibonacci(x, 0, 1)
}

NESL

Recursive

function fib(n) = if n < 2 then n else fib(n - 2) + fib(n - 1);

NetRexx

Translation of: REXX
/* NetRexx */

options replace format comments java crossref savelog symbols

numeric digits 210000                  /*prepare for some big 'uns.     */
parse arg x y .                        /*allow a single number or range.*/
if x == '' then do                     /*no input? Then assume -30-->+30*/
  x = -30
  y = -x
  end

if y == '' then y = x             /*if only one number, show fib(n)*/
loop k = x to y                   /*process each Fibonacci request.*/
  q = fib(k)
  w = q.length                    /*if wider than 25 bytes, tell it*/
  say 'Fibonacci' k"="q
  if w > 25 then say 'Fibonacci' k "has a length of" w
  end k
exit

/*-------------------------------------FIB subroutine (non-recursive)---*/
method fib(arg) private static
  parse arg n
  na = n.abs

  if na < 2 then return na             /*handle special cases.          */
  a = 0
  b = 1

  loop j = 2 to na
    s = a + b
    a = b
    b = s
    end j

  if n > 0 | na // 2 == 1 then return  s /*if positive or odd negative... */
                          else return -s /*return a negative Fib number.  */

NewLISP

Iterative

(define (fibonacci n)
    (let (L '(0 1))
        (dotimes (i n)
            (setq L (list (L 1) (apply + L))))
        (L 1)) )

Recursive

(define (fibonacci n)
(if (< n 2) 1
    (+ (fibonacci (- n 1))  
       (fibonacci (- n 2)))))

Matrix multiplication

(define (fibonacci n)
  (letn (f '((0 1) (1 1)) fib f)
    (dotimes (i n)
        (set 'fib (multiply fib f)))
    (fib 0 1)) )

(print(fibonacci 10)) ;;89

With a stack

;;;	Global variable (bigints); can be isolated in a namespace if need be
(setq stack '(0L 1L))
;
;;;	If the stack is too short, complete it; then read from it
;;;	Adding at the end of a list is optimized in NewLisp
(define (fib n)
	(while (<= (length stack) n)
		(push (+ (stack -1) (stack -2)) stack -1))
	(stack n))
;
;;; Test (~ 7+ s on my mediocre laptop)
;(println (time (fib 50000)))
;;;	or
(println (length (fib 50000)))
;;;	outputs 10450 (digits)

NGS

Iterative

Translation of: Python
F fib(n:Int) {
	n < 2 returns n
	local a = 1, b = 1
	# i is automatically local because of for()
	for(i=2; i<n; i=i+1) {
		local next = a + b
		a = b
		b = next
	}
	b
}

Nial

Iterative

On my machine, about 1.7s for 100,000 iterations, n=92. Maybe a few percent faster than iterative Python. Note that n>92 produces overflow; Python keeps going - single iteration with n=1,000,000 takes it about 15s.

fibi is op n {
  if n<2 then 
    n
  else 
    x1:=0; x2:=1; 
    for i with tell (n - 1) do 
      x:=x1+x2;
      x1:=x2;
      x2:=x;
    endfor;
    x2
  endif};

Iterative using fold. Slightly faster, <1.6s:

fibf is op n {1 pick ((n- 1) fold [1 pick, +] 0 1)};

Tacit verion of above. Slightly faster still, <1.4s:

fibf2 is 1 pick fold [1 pick, +] reverse (0 1 hitch) (-1+);

Recursive

Really slow (over 8s for single iteration, n=33). (Similar to time for recursive python version with n=37.)

fibr is op n {fork [2>, +, + [fibr (-1 +), fibr (-2 +)]] n};

...or tacit version. More than twice as fast (?) but still slow:

fibr2 is fork [2>, +, + [fibr2 (-1 +), fibr2 (-2 +)]];

Matrix

Matrix inner product (ip). This appears to be the fastest, about 1.0s for 100,000 iterations, n=92: Note that n>92 produces negative result.

fibm is op n {floor (0 1 pick (reduce ip (n reshape [2 2 reshape 1 1 1 0])))};

Could it look a little more like J? (Maybe 5% slower than above.)

$ is reshape;
~ is tr f op a b {b f a}; % Goes before verb, rather than after like in J;
_ is floor; % Not really J, but J-ish? (Cannot redefine "<.".);

fibm2 is _(0 1 pick reduce ip([2 2$1 1 1 0](~$)));

Alternate, not involving replicating matrix n times, but maybe 50% slower than the fastest matrix version above - similar speed to iterative:

fibm3 is op n {a:=2 2$1 1 1 0; _(0 1 pick ((n- 1) fold (a ip) a))};

Nim

Analytic

proc Fibonacci(n: int): int64 =
  var fn = float64(n)
  var p: float64 = (1.0 + sqrt(5.0)) / 2.0
  var q: float64 = 1.0 / p
  return int64((pow(p, fn) + pow(q, fn)) / sqrt(5.0))

Iterative

proc Fibonacci(n: int): int =
  var
    first = 0
    second = 1

  for i in 0 .. <n:
    swap first, second
    second += first

  result = first

Recursive

proc Fibonacci(n: int): int64 =
  if n <= 2:
    result = 1
  else:
    result = Fibonacci(n - 1) + Fibonacci(n - 2)

Tail-recursive

proc Fibonacci(n: int, current: int64, next: int64): int64 =
  if n == 0:
    result = current
  else:
    result = Fibonacci(n - 1, next, current + next)
proc Fibonacci(n: int): int64 =
  result = Fibonacci(n, 0, 1)

Continuations

iterator fib: int {.closure.} =
  var a = 0
  var b = 1
  while true:
    yield a
    swap a, b
    b = a + b

var f = fib
for i in 0.. <10:
  echo f()

Nix

fibonacci = n:
    if n <= 1 then n else (fibonacci (n - 1) + fibonacci (n - 2));

Oberon-2

Works with: oo2c Version 2
MODULE Fibonacci;
IMPORT
  Out := NPCT:Console;

PROCEDURE Fibs(VAR r: ARRAY OF LONGREAL);
VAR
  i: LONGINT;
BEGIN
  r[0] := 1.0; r[1] := 1.0;
  FOR i := 2 TO LEN(r) - 1 DO
    r[i] := r[i - 2] + r[i - 1];
  END
END Fibs;

PROCEDURE FibsR(n: LONGREAL): LONGREAL;
BEGIN
  IF n < 2. THEN
    RETURN n
  ELSE
    RETURN FibsR(n - 1) + FibsR(n - 2)
  END
END FibsR;

PROCEDURE Show(r: ARRAY OF LONGREAL);
VAR
  i: LONGINT;
BEGIN
  Out.String("First ");Out.Int(LEN(r),0);Out.String(" Fibonacci numbers");Out.Ln;
  FOR i := 0 TO LEN(r) - 1 DO
    Out.LongRealFix(r[i],8,0)
  END;
  Out.Ln
END Show;

PROCEDURE Gen(s: LONGINT);
VAR
  x: POINTER TO ARRAY OF LONGREAL;
BEGIN
  NEW(x,s);
  Fibs(x^);
  Show(x^)  
END Gen;

PROCEDURE GenR(s: LONGINT);
VAR
  i: LONGINT;
BEGIN
  Out.String("First ");Out.Int(s,0);Out.String(" Fibonacci numbers (Recursive)");Out.Ln;
  FOR i := 1 TO s DO  
    Out.LongRealFix(FibsR(i),8,0)
  END;
  Out.Ln  
END GenR;

BEGIN 
  Gen(10);
  Gen(20);
  GenR(10);
  GenR(20);
END Fibonacci.
Output:
First 10 Fibonacci numbers
      1.      1.      2.      3.      5.      8.     13.     21.     34.     55.
First 20 Fibonacci numbers
      1.      1.      2.      3.      5.      8.     13.     21.     34.     55.     89.    144.    233.    377.    610.    987.   1597.   2584.   4181.   6765.
First 10 Fibonacci numbers (Recursive)
      1.      1.      2.      3.      5.      8.     13.     21.     34.     55.
First 20 Fibonacci numbers (Recursive)
      1.      1.      2.      3.      5.      8.     13.     21.     34.     55.     89.    144.    233.    377.    610.    987.   1597.   2584.   4181.   6765.

Objeck

Recursive

bundle Default {
  class Fib {
    function : Main(args : String[]), Nil {
      for(i := 0; i <= 10; i += 1;) {
        Fib(i)->PrintLine();
      };
    }
    
    function : native : Fib(n : Int), Int {
      if(n < 2) {
        return n;
      };
      
      return Fib(n-1) + Fib(n-2);
    }
  }
}

Objective-C

Recursive

-(long)fibonacci:(int)position
{
    long result = 0;
    if (position < 2) {
        result = position;
    } else {
        result = [self fibonacci:(position -1)] + [self fibonacci:(position -2)];
    }
    return result;    
}

Iterative

+(long)fibonacci:(int)index {
    long beforeLast = 0, last = 1;
    while (index > 0) {
        last += beforeLast;
        beforeLast = last - beforeLast;
        --index;
    }
    return last;
}

OCaml

Tail-Recursive (fast)

let fib n =
  let rec aux i a b =
    if i = 0 then a else aux (pred i) b (a + b)
  in
  aux n 0 1

Iterative

let fib_iter n =
  if n < 2 then
    n
  else let fib_prev = ref 1
  and fib = ref 1 in
    for num = 2 to n - 1 do
      let temp = !fib in
        fib := !fib + !fib_prev;
        fib_prev := temp
    done;
    !fib

Recursive

let rec fib_rec n =
  if n < 2 then
    n
  else
    fib_rec (n - 1) + fib_rec (n - 2)

let rec fib = function 
    0 -> 0
  | 1 -> 1
  | n -> if n > 0 then fib (n-1) + fib (n-2)
         else fib (n+2) - fib (n+1)

Arbitrary Precision

Using OCaml's Num module.

open Num

let fib =
  let rec fib_aux f0 f1 = function
    | 0 -> f0
    | 1 -> f1
    | n -> fib_aux f1 (f1 +/ f0) (n - 1)
  in
  fib_aux (num_of_int 0) (num_of_int 1)

(* support for negatives *)
let fib n = 
      if n < 0 && n mod 2 = 0 then minus_num (fib (abs n))  
      else fib (abs n)
;;
(* It can be called from the command line with an argument *)
(* Result is send to standart output *)
let n = int_of_string Sys.argv.(1) in 
print_endline (string_of_num (fib n))

compile with:

ocamlopt nums.cmxa -o fib fib.ml

Output:

$ ./fib 0
0
$ ./fib 10
55
$ ./fib 399
108788617463475645289761992289049744844995705477812699099751202749393926359816304226
$ ./fib -6
-8

O(log(n)) with arbitrary precision

This performs log2(N) matrix multiplys. Each multiplication is not constant-time but increases sub-linearly, about O(log(N)).

open Num

let mul (a,b,c) (d,e,f) = let bxe = b*/e in
  (a*/d +/ bxe, a*/e +/ b*/f, bxe +/ c*/f)

let id = (Int 1, Int 0, Int 1)
let rec pow a n =
  if n=0 then id else
    let b = pow a (n/2) in
    if (n mod 2) = 0 then mul b b else mul a (mul b b)

let fib n =
  let (_,y,_) = (pow (Int 1, Int 1, Int 0) n) in
  string_of_num y
;;
Printf.printf "fib %d = %s\n" 300 (fib 300)

Output:

fib 300 = 222232244629420445529739893461909967206666939096499764990979600

Matrix Exponentiation

open List
;;
let rec bin n =
  if n < 2 then [n mod 2 = 1]
  else bin (n/2) @ [n mod 2 = 1]
;;
let cut = function
  | [] -> [] 
  | _ :: x -> x
;;
let multiply a b =
  let ((p, q), (r, s)) = a in
  let ((t, u), (v, w)) = b in
  ((p*t+q*v, p*u+q*w), (r*t+s*v, r*u+s*w))
;;
let fib n =
  let rec f p q r =
    if length r = 1 then
      if nth r 0 then (multiply p q, q)
      else (p, q)
    else
      let (pp, qq) = f p q (cut r) in
      let qqq = multiply qq qq in
      if nth r 0 then (multiply pp qqq, qqq)
      else (pp, qqq) in
  f ((1L, 0L), (0L, 1L)) ((1L, 1L), (1L, 0L)) (bin n) |> fst |> fst |> snd
;;

Octave

Recursive

% recursive
function fibo = recfibo(n)
  if ( n < 2 )
    fibo = n;
  else
    fibo = recfibo(n-1) + recfibo(n-2);
  endif
endfunction

Testing

% testing
for i = 0 : 20
  printf("%d %d\n", i, recfibo(i));
endfor

Iterative

% iterative
function fibo = iterfibo(n)
  if ( n < 2 )
    fibo = n;
  else
    f = zeros(2,1);
    f(1) = 0; 
    f(2) = 1;
    for i = 2 : n
      t = f(2);
      f(2) = f(1) + f(2);
      f(1) = t;
    endfor
    fibo = f(2);
  endif
endfunction

Testing

% testing
for i = 0 : 20
  printf("%d %d\n", i, iterfibo(i));
endfor

Analytic

function retval = fibanalytic(n)
  retval = round(((5 .^ 0.5 + 1) / 2) .^ n / 5 .^ 0.5);
endfunction

Tail Recursive

function retval = fibtailrecursive(n, prevfib = 0, fib = 1)
  if (n == 0)
    retval = prevfib;
  else
    retval = fibtailrecursive(n - 1, fib, prevfib + fib);
  endif
endfunction

Odin

Fibinacci Sequence - Iterative Solution
Odin Build: dev-2023-07-nightly:3072479c

package fib
import "core:fmt"

main :: proc() {
	fmt.println("\nFibonacci Seq - starting n and n+1 from 0 and 1:")
	fmt.println("------------------------------------------------")
	for j: u128 = 0; j <= 20; j += 1 {
		fmt.println("n:", j, "\tFib:", fibi(j))
	}
}

fibi :: proc(n: u128) -> u128 {
    if n < 2 {
        return n
    }
    a, b: u128 = 0, 1
    for _ in 2..=n {
        a += b
        a, b = b, a
    }
    return b
}
Output:
First 20 Fibonacci Numbers
Starting n and n+1 from 0 and 1
-------------------------------
n: 0    Fib: 0
n: 1    Fib: 1
n: 2    Fib: 1
n: 3    Fib: 2
n: 4    Fib: 3
n: 5    Fib: 5
n: 6    Fib: 8
n: 7    Fib: 13
n: 8    Fib: 21
n: 9    Fib: 34
n: 10   Fib: 55
n: 11   Fib: 89
n: 12   Fib: 144
n: 13   Fib: 233
n: 14   Fib: 377
n: 15   Fib: 610
n: 16   Fib: 987
n: 17   Fib: 1597
n: 18   Fib: 2584
n: 19   Fib: 4181
n: 20   Fib: 6765
-------------------------------

Oforth

: fib   0 1 rot #[ tuck + ] times drop ;

Ol

Same as Scheme example(s).

Onyx (wasm)

use core.iter
use core { printf }

// Procedural Simple For-Loop Style
fib_for_loop :: (n: i32) -> i32 {
    a: i32 = 0;
    b: i32 = 1;
    for 0 .. n {
        tmp := a;
        a = b;
        b = tmp + b;
    }
    return a;
}

FibState :: struct { a, b: u64 }

// Functional Folding Style
fib_by_fold :: (n: i32) => {
    end_state := 
        iter.counter()
        |> iter.take(n)
        |> iter.fold(
            FibState.{ a = 0, b = 1 },
            (_, state) => FibState.{
                a = state.b,
                b = state.a + state.b
            }
        );
    return end_state.a;
}

// Custom Iterator Style
fib_iterator :: (n: i32) => 
    iter.generator(
        &.{ a = cast(u64) 0, b = cast(u64) 1, counter = n },
        (state: & $Ctx) -> (u64, bool) {
            if state.counter <= 0 {
                return 0, false;
            }
            tmp := state.a;
            state.a = state.b;
            state.b = state.b + tmp;
            state.counter -= 1;
            return tmp, true;
        }
    );

main :: () {
    printf("\nBy For Loop:\n");
    for i in 0 .. 21 {
        printf("{} ", fib_for_loop(i));
    }

    printf("\n\nBy Iterator:\n");
    for i in 0 .. 21 {
        printf("{} ", fib_by_fold(i));
    }

    printf("\n\nBy Fold:\n");
    for value, index in fib_iterator(21) {
        printf("{} ", value);
    }
}
Output:
For-Loop:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765

Functional Fold:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765

Custom Iterator:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765

OPL

FIBON:
REM Fibonacci sequence is generated to the Organiser II floating point variable limit.
REM CLEAR/ON key quits.
REM Mikesan - http://forum.psion2.org/
LOCAL A,B,C
A=1 :B=1 :C=1
PRINT A,
DO
  C=A+B
  A=B
  B=C
  PRINT A,
UNTIL GET=1

Order

Recursive

#include <order/interpreter.h>

#define ORDER_PP_DEF_8fib_rec                     \
ORDER_PP_FN(8fn(8N,                               \
                8if(8less(8N, 2),                 \
                    8N,                           \
                    8add(8fib_rec(8sub(8N, 1)),   \
                         8fib_rec(8sub(8N, 2))))))

ORDER_PP(8fib_rec(10))

Tail recursive version (example supplied with language):

#include <order/interpreter.h>
 
#define ORDER_PP_DEF_8fib                                         \
ORDER_PP_FN(8fn(8N,                                               \
                8fib_iter(8N, 0, 1)))
 
#define ORDER_PP_DEF_8fib_iter                                    \
ORDER_PP_FN(8fn(8N, 8I, 8J,                                       \
                8if(8is_0(8N),                                    \
                    8I,                                           \
                    8fib_iter(8dec(8N), 8J, 8add(8I, 8J)))))
 
ORDER_PP(8to_lit(8fib(8nat(5,0,0))))

Memoization

#include <order/interpreter.h>

#define ORDER_PP_DEF_8fib_memo                                    \
ORDER_PP_FN(8fn(8N,                                               \
                8tuple_at(0, 8fib_memo_inner(8N, 8seq))))
                

#define ORDER_PP_DEF_8fib_memo_inner                                            \
ORDER_PP_FN(8fn(8N, 8M,                                                         \
                8cond((8less(8N, 8seq_size(8M)), 8pair(8seq_at(8N, 8M), 8M))    \
                      (8equal(8N, 0), 8pair(0, 8seq(0)))                        \
                      (8equal(8N, 1), 8pair(1, 8seq(0, 1)))                     \
                      (8else,                                                   \
                        8lets((8S, 8fib_memo_inner(8sub(8N, 2), 8M))            \
                              (8T, 8fib_memo_inner(8dec(8N), 8tuple_at(1, 8S))) \
                              (8U, 8add(8tuple_at(0, 8S), 8tuple_at(0, 8T))),   \
                              8pair(8U,                                         \
                                    8seq_append(8tuple_at(1, 8T), 8seq(8U))))))))
                    

ORDER_PP(
8for_each_in_range(8fn(8N,
                       8print(8to_lit(8fib_memo(8N)) (,) 8space)),
                   1, 21)
)

Oz

Iterative

Using mutable references (cells).

fun{FibI N}
  Temp = {NewCell 0}
  A = {NewCell 0}
  B = {NewCell 1}
in    
  for I in 1..N do
    Temp := @A + @B
    A := @B
    B := @Temp
  end
  @A
end

Recursive

Inefficient (blows up the stack).

fun{FibR N}
  if N < 2 then N
  else {FibR N-1} + {FibR N-2}
  end
end

Tail-recursive

Using accumulators.

fun{Fib N}
   fun{Loop N A B}
      if N == 0 then
	 B
      else
	 {Loop N-1 A+B A}
      end
   end
in    
   {Loop N 1 0}
end

Lazy-recursive

declare
  fun lazy {FiboSeq}
     {LazyMap
      {Iterate fun {$ [A B]} [B A+B] end [0 1]}
      Head}
  end

  fun {Head A|_} A end

  fun lazy {Iterate F I}
     I|{Iterate F {F I}}
  end

  fun lazy {LazyMap Xs F}
     case Xs of X|Xr then {F X}|{LazyMap Xr F}
     [] nil then nil
     end
  end
in
  {Show {List.take {FiboSeq} 8}}

PARI/GP

Built-in

fibonacci(n)

Matrix

fib(n)=([1,1;1,0]^n)[1,2]

Analytic

This uses the Binet form.

fib(n)=my(phi=(1+sqrt(5))/2);round((phi^n-phi^-n)/sqrt(5))

The second term can be dropped since the error is always small enough to be subsumed by the rounding.

fib(n)=round(((1+sqrt(5))/2)^n/sqrt(5))

Algebraic

This is an exact version of the above formula. quadgen(5) represents and the number is stored in the form . imag takes the coefficient of . This uses the relation

and hence real(quadgen(5)^n) would give the (n-1)-th Fibonacci number.

fib(n)=imag(quadgen(5)^n)

A more direct translation (note that ) would be

fib(n)=my(phi=quadgen(5));(phi^n-(-1/phi)^n)/(2*phi-1)

Combinatorial

This uses the generating function. It can be trivially adapted to give the first n Fibonacci numbers.

fib(n)=polcoeff(x/(1-x-x^2)+O(x^(n+1)),n)

Binary powering

fib(n)={
  if(n<=0,
    if(n,(-1)^(n+1)*fib(n),0)
  ,
    my(v=lucas(n-1));
    (2*v[1]+v[2])/5
  )
};
lucas(n)={
  if (!n, return([2,1]));
  my(v=lucas(n >> 1), z=v[1], t=v[2], pr=v[1]*v[2]);
  n=n%4;
  if(n%2,
    if(n==3,[v[1]*v[2]+1,v[2]^2-2],[v[1]*v[2]-1,v[2]^2+2])
  ,
    if(n,[v[1]^2+2,v[1]*v[2]+1],[v[1]^2-2,v[1]*v[2]-1])
  )
};

Recursive

fib(n)={
  if(n<2,
    n
  ,
    fib(n-1)+fib(n)
  )
};

Anonymous recursion

Works with: PARI/GP version 2.8.0+

This uses self() which gives a self-reference.

fib(n)={
  if(n<2,
    n
  ,
    my(s=self());
    s(n-2)+s(n-1)
  )
};

It can be used without being named:

apply(n->if(n<2,n,my(s=self());s(n-2)+s(n-1)), [1..10])

gives

Output:
%1 = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

Memoization

F=[];
fib(n)={
  if(n>#F,
    F=concat(F, vector(n-#F));
    F[n]=fib(n-1)+fib(n-2)
  ,
    if(n<2,
      n
    ,
      if(F[n],F[n],F[n]=fib(n-1)+fib(n-2))
    )
  );
}

Iterative

fib(n)={
  if(n<0,return((-1)^(n+1)*fib(n)));
  my(a=0,b=1,t);
  while(n,
    t=a+b;
    a=b;
    b=t;
    n--
  );
  a
};

Chebyshev

This solution uses Chebyshev polynomials of the second kind (Chyebyshev U-polynomials).

fib(n)=n--;polchebyshev(n,2,I/2)*I^n;

or

fib(n)=abs(polchebyshev(n-1,2,I/2));

Anti-Hadamard matrix

All n×n (0,1) lower Hessenberg matrices have determinant at most F(n). The n×n anti-Hadamard matrix[1] matches this upper bound, and hence can be used as an inefficient method for computing Fibonacci numbers of positive index. These matrices are the same as Matlab's type-3 "Dramadah" matrices, following a naming suggestion of C. L. Mallows according to Graham & Sloane.

matantihadamard(n)={
  matrix(n,n,i,j,
    my(t=j-i+1);
    if(t<1,t%2,t<3)
  );
}
fib(n)=matdet(matantihadamard(n))


Testing adjacent bits

The Fibonacci numbers can be characterized (for n > 0) as the number of n-bit strings starting and ending with 1 without adjacent 0s. This inefficient, exponential-time algorithm demonstrates:

fib(n)=
{
  my(g=2^(n+1)-1);
  sum(i=2^(n-1),2^n-1,
    bitor(i,i<<1)==g
  );
}

One-by-one

This code is purely for amusement and requires n > 1. It tests numbers in order to see if they are Fibonacci numbers, and waits until it has seen n of them.

fib(n)=my(k=0);while(n--,k++;while(!issquare(5*k^2+4)&&!issquare(5*k^2-4),k++));k

ParaCL

fibbonachi = func(x) : fibb
{
  res = 1;
  if (x > 1)
    res = fibb(x - 1) + fibb(x - 2);
  res;
}

Pascal

Analytic

function fib(n: integer):longInt;
const
  Sqrt5 = sqrt(5.0);
  C1 = ln((Sqrt5+1.0)*0.5);//ln( 1.618..)
//C2 = ln((1.0-Sqrt5)*0.5);//ln(-0.618 )) tsetsetse
  C2 = ln((Sqrt5-1.0)*0.5);//ln(+0.618 ))
begin
  IF n>0 then
  begin
    IF odd(n) then
      fib := round((exp(C1*n) + exp(C2*n) )/Sqrt5)
    else
      fib := round((exp(C1*n) - exp(C2*n) )/Sqrt5)
  end
  else
    Fibdirekt := 0
end;

Recursive

function fib(n: integer): integer;
 begin
  if (n = 0) or (n = 1)
   then
    fib := n
   else
    fib := fib(n-1) + fib(n-2)
 end;

Iterative

function fib(n: integer): integer;
var
  f0, f1, tmpf0, k: integer;
begin
  f1 := n;
  IF f1 >1 then
  begin
    k := f1-1;
    f0 := 0;
    f1 := 1;
    repeat
      tmpf0 := f0;
      f0 := f1;
      f1 := f1+tmpf0;
      dec(k);
    until k = 0;
  end
  else
    IF f1 < 0 then
      f1 := 0;
  fib := f1;
end;

Analytic2

function FiboMax(n: integer):Extended;  //maXbox
begin
   result:= (pow((1+SQRT5)/2,n)-pow((1-SQRT5)/2,n))/SQRT5   
end;


function Fibo_BigInt(n: integer): string;  //maXbox
  var tbig1, tbig2, tbig3: TInteger;
  begin 
    result:= '0'
    tbig1:= TInteger.create(1);  //temp
    tbig2:= TInteger.create(0);  //result (a)
    tbig3:= Tinteger.create(1);  //b
    for it:= 1 to n do begin
    	tbig1.assign(tbig2)
	   tbig2.assign(tbig3);
	   tbig1.add(tbig3);
	   tbig3.assign(tbig1);
	 end; 
    result:= tbig2.toString(false)
    tbig3.free;
    tbig2.free;
    tbig1.free; 
  end;

writeln(floattoStr(FiboMax(555))) >>>4.3516638122555E115

writeln(Fibo_BigInt(555)) >>>43516638122555047989641805373140394725407202037260729735885664398655775748034950972577909265605502785297675867877570

Doubling (iterative)

The Clojure solution gives a recursive version of the Fibonacci doubling algorithm. The code below is an iterative version, written in Free Pascal. The unsigned 64-bit integer type can hold Fibonacci numbers up to F[93].

program Fibonacci_console;

{$mode objfpc}{$H+}

uses SysUtils;

function Fibonacci( n : word) : uint64;
{
Starts with the pair F[0],F[1]. At each iteration, uses the doubling formulae
to pass from F[k],F[k+1] to F[2k],F[2k+1]. If the current bit of n (starting
from the high end) is 1, there is a further step to F[2k+1],F[2k+2].
}
var
  marker, half_n : word;
  f, g : uint64; // pair of consecutive Fibonacci numbers
  t, u : uint64; // -----"-----
begin
  // The values of F[0], F[1], F[2]  are assumed to be known
  case n of
    0 : result := 0;
    1, 2 : result := 1;
    else begin
      half_n := n shr 1;
      marker := 1;
      while marker <= half_n do marker := marker shl 1;

      // First time: current bit is 1 by construction,
      //   so go straight from F[0],F[1] to F[1],F[2].
      f := 1; // = F[1]
      g := 1; // = F[2]
      marker := marker shr 1;

      while marker > 1 do begin
        t := f*(2*g - f);
        u := f*f + g*g;
        if (n and marker = 0) then begin
          f := t;
          g := u;
        end
        else begin
          f := u;
          g := t + u;
        end;
        marker := marker shr 1;
      end;

      // Last time: we need only one of the pair.
      if (n and marker = 0) then
        result := f*(2*g - f)
      else
        result := f*f + g*g;
    end; // end else (i.e. n > 2)
  end; // end case
end;

// Main program
var
  n : word;
begin
  for n := 0 to 93 do
    WriteLn( SysUtils.Format( 'F[%2u] = %20u', [n, Fibonacci(n)]));
end.
Output:
F[ 0] =                    0
F[ 1] =                    1
F[ 2] =                    1
F[ 3] =                    2
F[ 4] =                    3
F[ 5] =                    5
F[ 6] =                    8
F[ 7] =                   13
[...]
F[90] =  2880067194370816120
F[91] =  4660046610375530309
F[92] =  7540113804746346429
F[93] = 12200160415121876738

PascalABC.NET

Uses functionality from Fibonacci n-step number sequences#PascalABC.NET

// Fibonacci sequence. Nigel Galloway: August 30th., 2022
begin
  unfold(nFib,0bi,1bi).ElementAt(1000).Println;
end.
43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875 

Perl

Iterative

sub fib_iter {
  my $n = shift;
  use bigint try => "GMP,Pari";
  my ($v2,$v1) = (-1,1);
  ($v2,$v1) = ($v1,$v2+$v1) for 0..$n;
  $v1;
}

Recursive

sub fibRec {
    my $n = shift;
    $n < 2 ? $n : fibRec($n - 1) + fibRec($n - 2);
}

Modules

Quite a few modules have ways to do this. Performance is not typically an issue with any of these until 100k or so. With GMP available, the first three are much faster at large values.

# Uses GMP method so very fast
use Math::AnyNum qw/fibonacci/;
say fibonacci(10000);

# Uses GMP method, so also very fast
use Math::GMP;
say Math::GMP::fibonacci(10000);

# Binary ladder, GMP if available, Pure Perl otherwise
use ntheory qw/lucasu/;
say lucasu(1, -1, 10000);

# All Perl
use Math::NumSeq::Fibonacci;
my $seq = Math::NumSeq::Fibonacci->new;
say $seq->ith(10000);

# All Perl
use Math::Big qw/fibonacci/;
say 0+fibonacci(10000);  # Force scalar context

# Perl, gives floating point *approximation*
use Math::Fibonacci qw/term/;
say term(10000);

Array accumulation

This solution accumulates all Fibonacci numbers up to n into an array of n+1 elements (to account for the zeroth Fibonacci number). When the loop reaches n, the function returns the last element of the array, i.e. the n-th Fibonacci number. This function only works for positive integers, but it can be easily extended into negatives.

Note that, without the use of big integer libraries, pure Perl switches to floats in scientific notation above n=93 and treats any number as infinite above n=1476 (see output). This behaviour could vary across Perl implementations.

sub fibonacci {
    my $n = shift;    
    
    return 0 if $n <  1;
    return 1 if $n == 1;
        
    my @numbers = (0, 1);

    push @numbers, $numbers[-1] + $numbers[-2] foreach 2 .. $n;
    
    return $numbers[-1];
}

print "Fibonacci($_) -> ", (fibonacci $_), "\n"
    foreach (0 .. 20, 50, 93, 94, 100, 200, 1000, 1476, 1477);
Output:
Fibonacci(0) -> 0
Fibonacci(1) -> 1
Fibonacci(2) -> 1
Fibonacci(3) -> 2
Fibonacci(4) -> 3
Fibonacci(5) -> 5
Fibonacci(6) -> 8
Fibonacci(7) -> 13
Fibonacci(8) -> 21
Fibonacci(9) -> 34
Fibonacci(10) -> 55
Fibonacci(11) -> 89
Fibonacci(12) -> 144
Fibonacci(13) -> 233
Fibonacci(14) -> 377
Fibonacci(15) -> 610
Fibonacci(16) -> 987
Fibonacci(17) -> 1597
Fibonacci(18) -> 2584
Fibonacci(19) -> 4181
Fibonacci(20) -> 6765
Fibonacci(50) -> 12586269025
Fibonacci(93) -> 12200160415121876738
Fibonacci(94) -> 1.97402742198682e+19
Fibonacci(100) -> 3.54224848179262e+20
Fibonacci(200) -> 2.8057117299251e+41
Fibonacci(1000) -> 4.34665576869374e+208
Fibonacci(1476) -> 1.3069892237634e+308
Fibonacci(1477) -> Inf

Phix

function fibonacci(integer n)     -- iterative, works for -ve numbers
atom a=0, b=1
    if n=0 then return 0 end if
    if abs(n)>=79 then ?9/0 end if  -- inaccuracies creep in above 78
    for i=1 to abs(n)-1 do
        {a,b} = {b,a+b}
    end for
    if n<0 and remainder(n,2)=0 then return -b end if
    return b
end function
 
for i=0 to 28 do
    if i then puts(1,", ") end if
    printf(1,"%d", fibonacci(i))
end for
puts(1,"\n")
Output:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811

Using native integers/atoms, errors creep in above 78, so the same program converted to use mpfr:

Library: Phix/mpfr
-- demo\rosetta\fibonacci.exw
with javascript_semantics
include mpfr.e

mpz res = NULL, prev, next
integer lastn
atom t0 = time()
function fibonampz(integer n) -- resumable, works for -ve numbers, yields mpz
    integer absn = abs(n)
    if res=NULL or absn!=abs(lastn)+1 then
        if res=NULL then
            prev = mpz_init(0)
            res = mpz_init(1)
            next = mpz_init()
        else
            if n==lastn then return res end if
        end if
        mpz_fib2_ui(res,prev,absn)
    else
        if lastn<0 and remainder(lastn,2)=0 then
            mpz_mul_si(res,res,-1)
        end if
        mpz_add(next,res,prev)
        {prev,res,next} = {res,next,prev}
    end if
    if n<0 and remainder(n,2)=0 then
        mpz_mul_si(res,res,-1)
    end if
    lastn = n
    return res
end function

for i=0 to 28 do
    if i then puts(1,", ") end if
    printf(1,"%s", {mpz_get_str(fibonampz(i))})
end for
puts(1,"\n")
printf(1,"%s\n", {mpz_get_str(fibonampz(705))})

-- not surprisingly JavaScript BigInt takes a bit
-- longer for 0.1M digits that gmp does for 1.0M:
integer big = iff(platform()==JS?478495:4784969)
string s = mpz_get_str(fibonampz(big))
?shorten(s)
?elapsed(time()-t0)
Output:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811
970066202977562212558683426760773016559904631977220423547980211057068777324159443678590358026859129109599109446646966713225742014317926940054191330
{1000000,"107273956418004772293648135962250043219...407167474856539211500699706378405156269"}
"2.1s"

Phixmonti

def Fibonacci
    dup 0 < if
        "Invalid argument: " print
    else 
        1 1 rot 2 -
        for
            drop
            over over +
        endfor
    endif
enddef

10 Fibonacci pstack print nl
-10 Fibonacci print

PHP

Iterative

function fibIter($n) {
    if ($n < 2) {
        return $n;
    }
    $fibPrev = 0;
    $fib = 1;
    foreach (range(1, $n-1) as $i) {
        list($fibPrev, $fib) = array($fib, $fib + $fibPrev);
    }
    return $fib;
}

Recursive

function fibRec($n) {
    return $n < 2 ? $n : fibRec($n-1) + fibRec($n-2);
}

Picat

Function

tabling for speed.

go =>
  println([fib_fun(I) : I in 1..10]),
  F1=fib_fun(2**10),
  println(f1=F1),
  nl.

table
fib_fun(0) = 0.
fib_fun(1) = 1.
fib_fun(N) = fib_fun(N-1) + fib_fun(N-2).
Output:
[1,1,2,3,5,8,13,21,34,55]
f1 = 4506699633677819813104383235728886049367860596218604830803023149600030645708721396248792609141030396244873266580345011219530209367425581019871067646094200262285202346655868899711089246778413354004103631553925405243

Array

fib_array(0,[0]).
fib_array(1,[0,1]).
fib_array(N,A) :-
   N > 1,
   A = new_array(N),
   A[1] = 1,
   A[2] = 1,
   foreach(I in 3..N)
     A[I] = A[I-1] + A[I-2]
   end.

Loop

fib_loop(N) = Curr =>
  Curr = 0,
  Prev = 1,
  foreach(_I in 1..N)
    Tmp = Curr,
    Curr := Curr + Prev,
    Prev := Tmp
  end.

Formula

Translation of: Tcl

Works for n <= 70.

fib_formula(N) = round((0.5 + 0.5*sqrt(5))**N / sqrt(5)).

"Lazy lists"

Translation of: Prolog
go =>fib_lazy(X),
  A = new_list(15),
  append(A,_,X),
  println(A),

fib_lazy([0,1|X]) :-
    ffib(0,1,X).
ffib(A,B,X) :-
    freeze(X, (C is A+B, X=[C|Y], ffib(B,C,Y)) ).
Output:
[0,1,1,2,3,5,8,13,21,34,55,89,144,233,377]

Generators idiom

Translation of: Prolog
go =>
  take(15, $fib_gen(0,1), $T-[], _G),
  println(T).

take( 0, Next, Z-Z, Next).
take( N, Next, [A|B]-Z, NZ):- N>0, !, next( Next, A, Next1),
  N1 is N-1,
  take( N1, Next1, $B-Z, NZ).
 
next( fib_gen(A,B), A, fib_gen(B,C)):- C is A+B.
Output:
[0,1,1,2,3,5,8,13,21,34,55,89,144,233,377]

Reversible

This is a reversible variant using constraint modelling.

fib_rev(N,F) has these two usages:

  • find F given a value N (this is the normal usage)
  • find N given a value F (backward usage)


Note: In general, Picat supports arbitrary precision for integers. However, the constraint solvers only supports integer domains of -2**56..2**56 so the largest Fibonacci number that can be found by this predicate is N = 81.


import cp.

go =>
  N1 = 30,
  fib_rev(30,F1),
  println([n1=N1,fib1=F1]),
  
  F2 #= 20365011074,
  fib_rev(N2,F2),
  println([n2=N2,f2=F2]),
  
  F3 = 61305790721611591,
  fib_rev(N3,F3),
  println([n3=N3,F3]),
  nl.

table
fib_rev(0,1).
fib_rev(1,1).
fib_rev(N,F) :-
  N #> 0,
  F #> 0,
  N1 #= N-1, 
  N2 #= N-2,
  fib_rev(N1,F1), 
  fib_rev(N2,F2),  
  F #= F1+F2.
Output:
[n1 = 30,fib1 = 1346269]
[n2 = 50,f2 = 20365011074]
[n3 = 81,61305790721611591]

PicoLisp

Recursive

(de fibo (N)
   (if (>= 2 N)
      1
      (+ (fibo (dec N)) (fibo (- N 2))) ) )



Recursive with Cache

Using a recursive version doesn't need to be slow, as the following shows:

(de fibo (N)
   (cache '(NIL) N  # Use a cache to accelerate
      (if (>= 2 N)
         N
         (+ (fibo (dec N)) (fibo (- N 2))) ) ) )

(bench (fibo 1000))

Output:

0.012 sec
-> 43466557686937456435688527675040625802564660517371780402481729089536555417949
05189040387984007925516929592259308032263477520968962323987332247116164299644090
6533187938298969649928516003704476137795166849228875

Iterative

(de fib (N)
   (let (A 0  B 1)
      (do N
         (prog1 B (setq B (+ A B) A @)) ) ) )

Coroutines

(co 'fibo
   (let (A 0  B 1)
      (yield 'ready)
      (while
         (yield
            (swap 'B (+ (swap 'A B) B)) ) ) ) )

(do 15
   (printsp (yield 'next 'fibo)) )
(prinl)
(yield NIL 'fibo)
Output:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610

Pike

Iterative

int     
fibIter(int n) {
    int fibPrev, fib, i;
    if (n < 2) {
        return 1;
    }
    fibPrev = 0;
    fib = 1;
    for (i = 1; i < n; i++) {
        int oldFib = fib;
        fib += fibPrev;
        fibPrev = oldFib;
    }
    return fib;
}

Recursive

int 
fibRec(int n) {
    if (n < 2) {
        return(1);
    }
    return( fib(n-2) + fib(n-1) );
}

PIR

Recursive:

Works with: Parrot version tested with 2.4.0
.sub fib
  .param int n
  .local int nt
  .local int ft
  if n < 2 goto RETURNN
  nt = n - 1
  ft = fib( nt )
  dec nt
  nt = fib(nt)
  ft = ft + nt
  .return( ft )
RETURNN:
  .return( n )
  end
.end

.sub main :main
  .local int counter
  .local int f
  counter=0
LOOP: 
  if counter > 20 goto DONE
  f = fib(counter)
  print f
  print "\n"
  inc counter
  goto LOOP
DONE:
  end
.end

Iterative (stack-based):

Works with: Parrot version tested with 2.4.0
.sub fib
  .param int n
  .local int counter
  .local int f
  .local pmc fibs
  .local int nmo
  .local int nmt

  fibs = new 'ResizableIntegerArray'
  if n == 0 goto RETURN0
  if n == 1 goto RETURN1
  push fibs, 0
  push fibs, 1
  counter = 2
FIBLOOP:
  if counter > n goto DONE
  nmo = pop fibs
  nmt = pop fibs
  f = nmo + nmt
  push fibs, nmt
  push fibs, nmo
  push fibs, f
  inc counter
  goto FIBLOOP
RETURN0:
  .return( 0 )
  end
RETURN1:
  .return( 1 )
  end
DONE:
  f = pop fibs
  .return( f )
  end
.end

.sub main :main
  .local int counter
  .local int f
  counter=0
LOOP: 
  if counter > 20 goto DONE
  f = fib(counter)
  print f
  print "\n"
  inc counter
  goto LOOP
DONE:
  end
.end

PL/0

The program waits for n. Then it displays nth Fibonacci number.

var n, a, b, i, tmp;
begin
  ? n;
  a := 0; b := 1;
  i := 2;
  while i <= n do
  begin
    tmp := b; b := a + b; a := tmp;
    i := i + 1
  end;
  ! b
end.

4 runs.

Input:
5
Output:
       5
Input:
9
Output:
      34
Input:
13
Output:
     233
Input:
20
Output:
    6765

PL/I

/* Form the n-th Fibonacci number, n > 1.    12 March 2022 */
Fib: procedure (n) returns (fixed binary (31));
   declare (i, n, f1, f2, f3) fixed binary (31);

   f1 = 0; f2 = 1;
   do i = 1 to n-2;
      f3 = f1 + f2;
      f1 = f2;
      f2 = f3;
   end;
   return (f3);

end Fib;

PL/M

100H:
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;

PRINT$NUMBER: PROCEDURE (N);
    DECLARE S (6) BYTE INITIAL ('.....$');
    DECLARE (N, P) ADDRESS, C BASED P BYTE;
    P = .S(5);
DIGIT:
    P = P - 1;
    C = N MOD 10 + '0';
    N = N / 10;
    IF N > 0 THEN GO TO DIGIT;
    CALL PRINT(P);
END PRINT$NUMBER;

FIBONACCI: PROCEDURE (N) ADDRESS;
    DECLARE (N, A, B, C, I) ADDRESS;
    IF N<=1 THEN RETURN N;
    A = 0;
    B = 1;
    DO I=2 TO N;
        C = A;
        A = B;
        B = A + C;
    END;
    RETURN B;
END FIBONACCI;

DECLARE I ADDRESS;
DO I=0 TO 20;
    CALL PRINT$NUMBER(FIBONACCI(I));
    CALL PRINT(.' $');
END;
CALL EXIT;
EOF
Output:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765

PL/pgSQL

Recursive

CREATE OR REPLACE FUNCTION fib(n INTEGER) RETURNS INTEGER AS $$
BEGIN
  IF (n < 2) THEN
    RETURN n;
  END IF;
  RETURN fib(n - 1) + fib(n - 2);
END;
$$ LANGUAGE plpgsql;

Calculated

CREATE OR REPLACE FUNCTION fibFormula(n INTEGER) RETURNS INTEGER AS $$
BEGIN
  RETURN round(pow((pow(5, .5) + 1) / 2, n) / pow(5, .5));
END;
$$ LANGUAGE plpgsql;

Linear

CREATE OR REPLACE FUNCTION fibLinear(n INTEGER) RETURNS INTEGER AS $$
DECLARE
  prevFib INTEGER := 0;
  fib INTEGER := 1;
BEGIN
  IF (n < 2) THEN
    RETURN n;
  END IF;

  WHILE n > 1 LOOP
    SELECT fib, prevFib + fib INTO prevFib, fib;
    n := n - 1;
  END LOOP;

  RETURN fib;
END;
$$ LANGUAGE plpgsql;

Tail recursive

CREATE OR REPLACE FUNCTION fibTailRecursive(n INTEGER, prevFib INTEGER DEFAULT 0, fib INTEGER DEFAULT 1)
RETURNS INTEGER AS $$
BEGIN
  IF (n = 0) THEN
    RETURN prevFib;
  END IF;
  RETURN fibTailRecursive(n - 1, fib, prevFib + fib);
END;
$$ LANGUAGE plpgsql;

PL/SQL

create or replace function fnu_fibonacci(p_num integer) return integer is
  f integer;
  p integer;
  q integer;
begin
  case when p_num < 0 or p_num != trunc(p_num) 
                            then raise_application_error(-20001, 'Invalid input: ' || p_num, true);
       when p_num in (0, 1) then f := p_num;
       else
            p := 0;
            q := 1;
            for i in 2 .. p_num loop
              f := p + q;
              p := q;
              q := f;
            end loop;
  end case;
  return(f);
end fnu_fibonacci;
/

Plain English

To find a fibonacci number given a count:
Put 0 into a number.
Put 1 into another number.
Loop.
If a counter is past the count, put the number into the fibonacci number; exit.
Add the number to the other number.
Swap the number with the other number.
Repeat.

Pop11

define fib(x);
lvars a , b;
    1 -> a;
    1 -> b;
    repeat x - 1 times
         (a + b, b) -> (b, a);
    endrepeat;
    a;
enddefine;

PostScript

Enter the desired number for "n" and run through your favorite postscript previewer or send to your postscript printer:

%!PS

% We want the 'n'th fibonacci number
/n 13 def

% Prepare output canvas:
/Helvetica findfont 20 scalefont setfont
100 100 moveto

%define the function recursively:
/fib { dup 
       3 lt
         { pop 1 }
         { dup 1 sub fib exch 2 sub fib add }
       ifelse
    } def
    
    (Fib\() show n (....) cvs show (\)=) show n fib (.....) cvs show

showpage

Potion

Recursive

Starts with int and upgrades on-the-fly to doubles.

recursive = (n):
  if (n <= 1): 1. else: recursive (n - 1) + recursive (n - 2)..

n = 40
("fib(", n, ")= ", recursive (n), "\n") join print
recursive(40)= 165580141
real	0m2.851s

Iterative

iterative = (n) :
   curr = 0
   prev = 1
   tmp = 0
   n times:
      tmp = curr
      curr = curr + prev
      prev = tmp
   .
   curr
.

Matrix based

sqr = (x): x * x.

# Based on the fact that
# F2n = Fn(2Fn+1 - Fn)
# F2n+1 = Fn ^2 + Fn+1 ^2
matrix = (n) :
   algorithm = (n) :
      "computes (Fn, Fn+1)"
      if (n < 2): return ((0, 1), (1, 1)) at(n).
      
      # n = e + {0, 1}
      q = algorithm(n / 2)  # q = (Fe/2, Fe/2+1)
      q = (q(0) * (2 * q(1) - q(0)), sqr(q(0)) + sqr(q(1)))  # q => (Fe, Fe+1)
      if (n % 2 == 1) :  # q => (Fe+{0, 1}, Fe+1+{0,1}) = (Fn, Fn+1)
         q = (q(1), q(1) + q(0))
      .
      q
   .
   algorithm(n)(0)
.

Handling negative values

fibonacci = (n) :
   myFavorite = matrix
   if (n >= 0) :
      myFavorite(n)
   .  else :
      n = n * -1
      if (n % 2 == 1) :
         myFavorite(n)
      . else :
         myFavorite(n) * -1
      .
   .
.

PowerShell

Iterative

function FibonacciNumber ( $count )
{
    $answer = @(0,1)
    while ($answer.Length -le $count)
    {
        $answer += $answer[-1] + $answer[-2]
    }
    return $answer
}

An even shorter version that eschews function calls altogether:

$count = 8
$answer = @(0,1)
0..($count - $answer.Length) | Foreach { $answer += $answer[-1] + $answer[-2] }
$answer

Recursive

function fib($n) {
    switch ($n) {
        0            { return 0 }
        1            { return 1 }
        { $_ -lt 0 } { return [Math]::Pow(-1, -$n + 1) * (fib (-$n)) }
        default      { return (fib ($n - 1)) + (fib ($n - 2)) }
    }
}

Processing

Translation of: Java
void setup() {
  size(400, 400);
  fill(255, 64);
  frameRate(2);
}
void draw() {
  int num = fibonacciNum(frameCount);
  println(frameCount, num);
  rect(0,0,num, num);
  if(frameCount==14) frameCount = -1; // restart
}
int fibonacciNum(int n) {
  return (n < 2) ? n : fibonacciNum(n - 1) + fibonacciNum(n - 2);
}

On the nth frame, the nth Fibonacci number is printed to the console and a square of that size is drawn on the sketch surface. The sketch restarts to keep drawing within the window size.

Output:
1
1
2
3
5
8
13
21
34
55
89
144
233
377

Prolog

Works with: SWI Prolog
Works with: GNU Prolog
Works with: YAP
fib(1, 1) :- !.
fib(0, 0) :- !.
fib(N, Value) :-
  A is N - 1, fib(A, A1),
  B is N - 2, fib(B, B1),
  Value is A1 + B1.

This naive implementation works, but is very slow for larger values of N. Here are some simple measurements (in SWI-Prolog):

?- time(fib(0,F)).
% 2 inferences, 0.000 CPU in 0.000 seconds (88% CPU, 161943 Lips)
F = 0.

?- time(fib(10,F)).
% 265 inferences, 0.000 CPU in 0.000 seconds (98% CPU, 1458135 Lips)
F = 55.

?- time(fib(20,F)).
% 32,836 inferences, 0.016 CPU in 0.016 seconds (99% CPU, 2086352 Lips)
F = 6765.

?- time(fib(30,F)).
% 4,038,805 inferences, 1.122 CPU in 1.139 seconds (98% CPU, 3599899 Lips)
F = 832040.

?- time(fib(40,F)).
% 496,740,421 inferences, 138.705 CPU in 140.206 seconds (99% CPU, 3581264 Lips)
F = 102334155.

As you can see, the calculation time goes up exponentially as N goes higher.

Poor man's memoization

Works with: SWI Prolog
Works with: YAP
Works with: GNU Prolog

The performance problem can be readily fixed by the addition of two lines of code (the first and last in this version):

%:- dynamic fib/2.  % This is ISO, but GNU doesn't like it.
:- dynamic(fib/2).  % Not ISO, but works in SWI, YAP and GNU unlike the ISO declaration.
fib(1, 1) :- !.
fib(0, 0) :- !.
fib(N, Value) :-
  A is N - 1, fib(A, A1),
  B is N - 2, fib(B, B1),
  Value is A1 + B1,
  asserta((fib(N, Value) :- !)).

Let's take a look at the execution costs now:

?- time(fib(0,F)).
% 2 inferences, 0.000 CPU in 0.000 seconds (90% CPU, 160591 Lips)
F = 0.

?- time(fib(10,F)).
% 37 inferences, 0.000 CPU in 0.000 seconds (96% CPU, 552610 Lips)
F = 55.

?- time(fib(20,F)).
% 41 inferences, 0.000 CPU in 0.000 seconds (96% CPU, 541233 Lips)
F = 6765.

?- time(fib(30,F)).
% 41 inferences, 0.000 CPU in 0.000 seconds (95% CPU, 722722 Lips)
F = 832040.

?- time(fib(40,F)).
% 41 inferences, 0.000 CPU in 0.000 seconds (96% CPU, 543572 Lips)
F = 102334155.

In this case by asserting the new N,Value pairing as a rule in the database we're making the classic time/space tradeoff. Since the space costs are (roughly) linear by N and the time costs are exponential by N, the trade-off is desirable. You can see the poor man's memoizing easily:

?- listing(fib).
:- dynamic fib/2.

fib(40, 102334155) :- !.
fib(39, 63245986) :- !.
fib(38, 39088169) :- !.
fib(37, 24157817) :- !.
fib(36, 14930352) :- !.
fib(35, 9227465) :- !.
fib(34, 5702887) :- !.
fib(33, 3524578) :- !.
fib(32, 2178309) :- !.
fib(31, 1346269) :- !.
fib(30, 832040) :- !.
fib(29, 514229) :- !.
fib(28, 317811) :- !.
fib(27, 196418) :- !.
fib(26, 121393) :- !.
fib(25, 75025) :- !.
fib(24, 46368) :- !.
fib(23, 28657) :- !.
fib(22, 17711) :- !.
fib(21, 10946) :- !.
fib(20, 6765) :- !.
fib(19, 4181) :- !.
fib(18, 2584) :- !.
fib(17, 1597) :- !.
fib(16, 987) :- !.
fib(15, 610) :- !.
fib(14, 377) :- !.
fib(13, 233) :- !.
fib(12, 144) :- !.
fib(11, 89) :- !.
fib(10, 55) :- !.
fib(9, 34) :- !.
fib(8, 21) :- !.
fib(7, 13) :- !.
fib(6, 8) :- !.
fib(5, 5) :- !.
fib(4, 3) :- !.
fib(3, 2) :- !.
fib(2, 1) :- !.
fib(1, 1) :- !.
fib(0, 0) :- !.
fib(A, D) :-
	B is A+ -1,
	fib(B, E),
	C is A+ -2,
	fib(C, F),
	D is E+F,
	asserta((fib(A, D):-!)).

All of the interim N/Value pairs have been asserted as facts for quicker future use, speeding up the generation of the higher Fibonacci numbers.

Continuation passing style

Works with SWI-Prolog and module lambda, written by Ulrich Neumerkel found there http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl

:- use_module(lambda).
fib(N, FN) :-
	cont_fib(N, _, FN, \_^Y^_^U^(U = Y)).

cont_fib(N, FN1, FN, Pred) :-
	(   N < 2 ->
	    call(Pred, 0, 1, FN1, FN)
	;
	    N1 is N - 1,
	    P = \X^Y^Y^U^(U is X + Y),
	    cont_fib(N1, FNA, FNB, P),
	    call(Pred, FNA, FNB, FN1, FN)
	).

With lazy lists

Works with SWI-Prolog and others that support freeze/2.

fib([0,1|X]) :-
    ffib(0,1,X).
ffib(A,B,X) :-
    freeze(X, (C is A+B, X=[C|Y], ffib(B,C,Y)) ).

The predicate fib(Xs) unifies Xs with an infinite list whose values are the Fibonacci sequence. The list can be used like this:

?- fib(X), length(A,15), append(A,_,X), writeln(A).
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]

Generators idiom

take( 0, Next, Z-Z, Next).
take( N, Next, [A|B]-Z, NZ):- N>0, !, next( Next, A, Next1),
  N1 is N-1,
  take( N1, Next1, B-Z, NZ).

next( fib(A,B), A, fib(B,C)):- C is A+B.

%% usage: ?- take(15, fib(0,1), _X-[], G), writeln(_X).
%% [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
%% G = fib(610, 987)

Yet another implementation

One of my favorites; loosely similar to the first example, but without the performance penalty, and needs nothing special to implement. Not even a dynamic database predicate. Attributed to M.E. for the moment, but simply because I didn't bother to search for the many people who probably did it like this long before I did. If someone knows who came up with it first, please let us know.

% Fibonacci sequence generator
fib(C, [P,S], C, N)  :- N is P + S.
fib(C, [P,S], Cv, V) :- succ(C, Cn), N is P + S, !, fib(Cn, [S,N], Cv, V).

fib(0, 0).
fib(1, 1).
fib(C, N) :- fib(2, [0,1], C, N). % Generate from 3rd sequence on

Looking at performance:

 ?- time(fib(30,X)).
% 86 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)
X = 832040 
 ?- time(fib(40,X)).
% 116 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)
X = 102334155
 ?- time(fib(100,X)).
% 296 inferences, 0.000 CPU in 0.001 seconds (0% CPU, Infinite Lips)
X = 354224848179261915075 

What I really like about this one, is it is also a generator- i.e. capable of generating all the numbers in sequence needing no bound input variables or special Prolog predicate support (such as freeze/3 in the previous example):

?- time(fib(X,Fib)).
% 0 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)
X = Fib, Fib = 0 ;
% 1 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)
X = Fib, Fib = 1 ;
% 3 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)
X = 2,
Fib = 1 ;
% 5 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)
X = 3,
Fib = 2 ;
% 5 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)
X = 4,
Fib = 3 ;
% 5 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)
X = Fib, Fib = 5 ;
% 5 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)
X = 6,
Fib = 8
...etc.

It stays at 5 inferences per iteration after X=3. Also, quite useful:

 ?- time(fib(100,354224848179261915075)).
% 296 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)
true .

?- time(fib(X,354224848179261915075)).
% 394 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)
X = 100 .

Efficient implementation

% John Devou: 26-Nov-2021
% Efficient program to calculate n-th Fibonacci number.
% Works fast for n ≤ 1 000 000 000.

b(0,Bs,Bs).
b(N,Bs,Res):- N > 0, B is mod(N,2), M is div(N,2), b(M,[B|Bs],Res).

f([],A,_,_,A).
f([X|Xs],A,B,C,Res):- AA is A^2, BB is B^2, A_ is 2*BB-3*AA-C, B_ is AA+BB,
    (X =:= 1 -> T is A_+B_, f(Xs,B_,T,-2,Res); f(Xs,A_,B_,2,Res)).

fib(N,F):- b(N,[],Bs), f(Bs,0,1,2,F), !.
Output:
?- time(fib(30,X)).
% 59 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)
X = 832040.

?- time(fib(100,X)).
% 80 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)
X = 354224848179261915075.

?- time(fib(500,X)). 
% 102 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)
X = 139423224561697880139724382870407283950070256587697307264108962948325571622863290691557658876222521294125.

?- time(fib(1000000000,_)). 
% 334 inferences, 7.078 CPU in 7.526 seconds (94% CPU, 47 Lips)
true.

Pure

Tail Recursive

fib n = loop 0 1 n with
  loop a b n = if n==0 then a else loop b (a+b) (n-1);
end;

Purity

The following takes a natural number and generates an initial segment of the Fibonacci sequence of that length:

data Fib1 = FoldNat 
            <
              const (Cons One (Cons One Empty)),
              (uncurry Cons) . ((uncurry Add) . (Head, Head . Tail), id)
            >

This following calculates the Fibonacci sequence as an infinite stream of natural numbers:

type (Stream A?,,,Unfold) = gfix X. A? . X?
data Fib2 = Unfold ((outl, (uncurry Add, outl))) ((curry id) One One)

As a histomorphism:

import Histo

data Fib3 = Histo . Memoize 
            <
              const One, 
              (p1 => 
              <
                const One, 
                (p2 => Add (outl $p1) (outl $p2)). UnmakeCofree
              > (outr $p1)) . UnmakeCofree
            >

Python

Analytic

Binet's formula:

from math import *

def analytic_fibonacci(n):
  sqrt_5 = sqrt(5);
  p = (1 + sqrt_5) / 2;
  q = 1/p;
  return int( (p**n + q**n) / sqrt_5 + 0.5 )

for i in range(1,31):
  print analytic_fibonacci(i),

Output:

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040

Iterative

def fibIter(n):
    if n < 2:
        return n
    fibPrev = 1
    fib = 1
    for _ in range(2, n):
        fibPrev, fib = fib, fib + fibPrev
    return fib

Iterative positive and negative

def fib(n,x=[0,1]):
   for i in range(abs(n)-1): x=[x[1],sum(x)]
   return x[1]*pow(-1,abs(n)-1) if n<0 else x[1] if n else 0

for i in range(-30,31): print fib(i),

Output:

-832040 514229 -317811 196418 -121393 75025 -46368 28657 -17711 10946 -6765 4181 -2584 1597 -987 
610 -377 233 -144 89 -55 34 -21 13 -8 5 -3 2 -1 1 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 
1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040

Recursive

def fibRec(n):
    if n < 2:
        return n
    else:
        return fibRec(n-1) + fibRec(n-2)

Recursive with Memoization

def fibMemo():
    pad = {0:0, 1:1}
    def func(n):
        if n not in pad:
            pad[n] = func(n-1) + func(n-2)
        return pad[n]
    return func

fm = fibMemo()
for i in range(1,31):
    print fm(i),

Output:

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040


Better Recursive doesn't need Memoization

The recursive code as written two sections above is incredibly slow and inefficient due to the nested recursion calls. Although the memoization above makes the code run faster, it is at the cost of extra memory use. The below code is syntactically recursive but actually encodes the efficient iterative process, and thus doesn't require memoization:

def fibFastRec(n):
    def fib(prvprv, prv, c):
        if c < 1: 
            return prvprv
        else: 
            return fib(prv, prvprv + prv, c - 1) 
    return fib(0, 1, n)

However, although much faster and not requiring memory, the above code can only work to a limited 'n' due to the limit on stack recursion depth by Python; it is better to use the iterative code above or the generative one below.

Generative

def fibGen(n):
    a, b = 0, 1
    while n>0:
        yield a
        a, b, n = b, a+b, n-1

Example use

>>> [i for i in fibGen(11)]

[0,1,1,2,3,5,8,13,21,34,55]

Matrix-Based

Translation of the matrix-based approach used in F#.

def prevPowTwo(n):
    'Gets the power of two that is less than or equal to the given input'
    if ((n & -n) == n):
        return n
    else:
        n -= 1
        n |= n >> 1
        n |= n >> 2
        n |= n >> 4
        n |= n >> 8
        n |= n >> 16
        n += 1
        return (n/2)

def crazyFib(n):
    'Crazy fast fibonacci number calculation'
    powTwo = prevPowTwo(n)
    
    q = r = i = 1
    s = 0
    
    while(i < powTwo):
        i *= 2
        q, r, s = q*q + r*r, r * (q + s), (r*r + s*s)
        
    while(i < n):
        i += 1
        q, r, s = q+r, q, r
        
    return q

Large step recurrence

This is much faster for a single, large value of n:

def fib(n, c={0:1, 1:1}):
    if n not in c:
        x = n // 2
        c[n] = fib(x-1) * fib(n-x-1) + fib(x) * fib(n - x)
    return c[n]

fib(10000000)  # calculating it takes a few seconds, printing it takes eons

Same as above but slightly faster

Putting the dictionary outside the function makes this about 2 seconds faster, could just make a wrapper:

F = {0: 0, 1: 1, 2: 1}
def fib(n):
    if n in F:
        return F[n]
    f1 = fib(n // 2 + 1)
    f2 = fib((n - 1) // 2)
    F[n] = (f1 * f1 + f2 * f2 if n & 1 else f1 * f1 - f2 * f2)
    return F[n]

Generative with Recursion

This can get very slow and uses a lot of memory. Can be sped up by caching the generator results.

def fib():
    """Yield fib[n+1] + fib[n]"""
    yield 1  # have to start somewhere
    lhs, rhs = fib(), fib()
    yield next(lhs) # move lhs one iteration ahead
    while True:
        yield next(lhs)+next(rhs)

f=fib()
print [next(f) for _ in range(9)]

Output:

[1, 1, 2, 3, 5, 8, 13, 21, 34]

Another version of recursive generators solution, starting from 0

from itertools import islice

def fib():
    yield 0
    yield 1
    a, b = fib(), fib()
    next(b)
    while True:
        yield next(a)+next(b)
 
print(tuple(islice(fib(), 10)))

As a scan or a fold

itertools.accumulate

The Fibonacci series can be defined quite simply and efficiently as a scan or accumulation, in which the accumulator is a pair of the two last numbers.

Works with: Python version 3.7
'''Fibonacci accumulation'''

from itertools import accumulate, chain
from operator import add


# fibs :: Integer :: [Integer]
def fibs(n):
    '''An accumulation of the first n integers in
       the Fibonacci series. The accumulator is a
       pair of the two preceding numbers.
    '''
    def go(ab, _):
        return ab[1], add(*ab)

    return [xy[1] for xy in accumulate(
        chain(
            [(0, 1)],
            range(1, n)
        ),
        go
    )]


# MAIN ---
if __name__ == '__main__':
    print(
        'First twenty: ' + repr(
            fibs(20)
        )
    )
Output:
First twenty: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]

functools.reduce

A fold can be understood as an amnesic scan, and functools.reduce can provide a useful and efficient re-write of the scanning version above, if we only need the Nth term in the series:

Works with: Python version 3.7
'''Nth Fibonacci term (by folding)'''

from functools import reduce
from operator import add


# nthFib :: Integer -> Integer
def nthFib(n):
    '''Nth integer in the Fibonacci series.'''
    def go(ab, _):
        return ab[1], add(*ab)
    return reduce(go, range(1, n), (0, 1))[1]


# MAIN ---
if __name__ == '__main__':
    print(
        '1000th term: ' + repr(
            nthFib(1000)
        )
    )
Output:
1000th term: 43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875
Works with: Python version 3.9
def fib(n):
    from functools import reduce
    return reduce(lambda x, y: (x[1], x[0] + x[1]), range(n), (0, 1))[0]

Array and Range

fibseq = [1,1,]
fiblength = 21
for x in range(1,fiblength-1):
	xcount = fibseq[x-1] + fibseq[x]
	fibseq.append(xcount)
print(xcount)
Output:
10946

Minimal from Russia

fi1=fi2=fi3=1 # FIB Russia rextester.com/FEEJ49204
for da in range(1, 88): # Danilin
    print("."*(20-len(str(fi3))), end=' ')
    print(fi3)
    fi3 = fi2+fi1
    fi1 = fi2
    fi2 = fi3
Output:
................... 1
................... 2
................... 3

....... 6557470319842
...... 10610209857723
...... 17167680177565

.. 420196140727489673
.. 679891637638612258
. 1100087778366101931

Qi

Recursive

(define fib
  0 -> 0
  1 -> 1
  N -> (+ (fib-r (- N 1))
          (fib-r (- N 2))))

Iterative

(define fib-0
  V2 V1 0 -> V2
  V2 V1 N -> (fib-0 V1 (+ V2 V1) (1- N)))

(define fib
  N -> (fib-0 0 1 N))

Quackery

  [ 0 1 rot times [ tuck + ] drop ] is fibo ( n --> n )

  100 fibo echo
Output:
354224848179261915075

R

Iterative positive and negative

fib=function(n,x=c(0,1)) {
   if (abs(n)>1) for (i in seq(abs(n)-1)) x=c(x[2],sum(x))
   if (n<0) return(x[2]*(-1)^(abs(n)-1)) else if (n) return(x[2]) else return(0)
}  

sapply(seq(-31,31),fib)

Output:

 [1] 1346269 -832040  514229 -317811  196418 -121393   75025  -46368   28657
[10]  -17711   10946   -6765    4181   -2584    1597    -987     610    -377
[19]     233    -144      89     -55      34     -21      13      -8       5
[28]      -3       2      -1       1       0       1       1       2       3
[37]       5       8      13      21      34      55      89     144     233
[46]     377     610     987    1597    2584    4181    6765   10946   17711
[55]   28657   46368   75025  121393  196418  317811  514229  832040 1346269

Other methods

# recursive
recfibo <- function(n) {
  if ( n < 2 ) n
  else Recall(n-1) + Recall(n-2)
}

# print the first 21 elements
print.table(lapply(0:20, recfibo))

# iterative
iterfibo <- function(n) {
  if ( n < 2 )
    n
  else {
    f <- c(0, 1)
    for (i in 2:n) {
      t <- f[2]
      f[2] <- sum(f)
      f[1] <- t
    }
    f[2]
  }
}

print.table(lapply(0:20, iterfibo))

# iterative but looping replaced by map-reduce'ing
funcfibo <- function(n) {
  if (n < 2) 
    n
  else {
    generator <- function(f, ...) {
      c(f[2], sum(f))
    }
    Reduce(generator, 2:n, c(0,1))[2]
  }
}

print.table(lapply(0:20, funcfibo))

Note that an idiomatic way to implement such low level, basic arithmethic operations in R is to implement them C and then call the compiled code.

Output:

All three solutions print

 [1] 0    1    1    2    3    5    8    13   21   34   55   89   144  233  377 
[16] 610  987  1597 2584 4181 6765

Ra

class FibonacciSequence
	**Prints the nth fibonacci number**
	
	on start
		
		args := program arguments
		
		if args empty
			print .fibonacci(8)
		
		else
			
			try
				print .fibonacci(integer.parse(args[0]))
			
			catch FormatException
				print to Console.error made !, "Input must be an integer"
				exit program with error code
			
			catch OverflowException
				print to Console.error made !, "Number too large"
				exit program with error code
	
	define fibonacci(n as integer) as integer is shared
		**Returns the nth fibonacci number**
		
		test
			assert fibonacci(0) = 0
			assert fibonacci(1) = 1
			assert fibonacci(2) = 1
			assert fibonacci(3) = 2
			assert fibonacci(4) = 3
			assert fibonacci(5) = 5
			assert fibonacci(6) = 8
			assert fibonacci(7) = 13
			assert fibonacci(8) = 21

		
		body
			a, b := 0, 1
		
			for n
				a, b := b, a + b
		
			return a

Racket

Tail Recursive

(define (fib n)
  (let loop ((cnt 0) (a 0) (b 1))
    (if (= n cnt)
        a
        (loop (+ cnt 1) b (+ a b)))))
(define (fib n (a 0) (b 1))
  (if (< n 2)
      1
      (+ a (fib (- n 1) b (+ a b)))))

Matrix Form

#lang racket

(require math/matrix)

(define (fibmat n) (matrix-ref 
                    (matrix-expt (matrix ([1 1]
                                          [1 0])) 
                                 n) 
                    1 0))

(fibmat 1000)

Foldl Form

(define (fib n)
  (car (foldl (lambda (y x)
                (let ((a (car x)) (b (cdr x)))
                  (cons b (+ a b)))) (cons 0 1) (range n))))

Raku

(formerly Perl 6)

List Generator

This constructs the fibonacci sequence as a lazy infinite list.

constant @fib = 0, 1, *+* ... *;

If you really need a function for it:

sub fib ($n) { @fib[$n] }

To support negative indices:

constant @neg-fib = 0, 1, *-* ... *;
sub fib ($n) { $n >= 0 ?? @fib[$n] !! @neg-fib[-$n] }

Iterative

sub fib (Int $n --> Int) {
    $n > 1 or return $n;
    my ($prev, $this) = 0, 1;
    ($prev, $this) = $this, $this + $prev for 1 ..^ $n;
    return $this;
}

Recursive

proto fib (Int $n --> Int) {*}
multi fib (0)  { 0 }
multi fib (1)  { 1 }
multi fib ($n) { fib($n - 1) + fib($n - 2) }

Rapira

Iterative

fun fibonacci(n)
    if n = 0 then
        return 0
    fi
    if n = 1 then
        return 1
    fi
    return fibonacci(n - 1) + fibonacci(n - 2)
end

RASEL

1&-:?v2\:2\01\--2\
     >$.@

RATFOR

program Fibonacci
#
integer*4 count, loop
integer*4 num1, num2, fib 

1 format(A)
2 format(I4)
3 format(I6,' ')
4 format(' ')
write(6,1,advance='no')'How Many: '
read(5,2)count

num1 = 0
num2 = 1
write(6,3,advance='no')num1
write(6,3,advance='no')num2

for (loop = 3; loop<=count; loop=loop+1)
      {
          fib = num1 + num2
          write(6,3,advance='no')fib
          num1 = num2
          num2 = fib
       }
write(6,4)
end


Red

(unnecessarily, but pleasantly palindromic)

Red []

palindrome: [fn: fn-1 + fn-1: fn]
fibonacci: func [n][
	fn-1: 0
	fn: 1
	loop n palindrome
]

Refal

$ENTRY Go {
    = <Prout <Repeat 18 Fibonacci 1 1>>
} ;

Repeat {
    0   s.F e.X = e.X;
    s.N s.F e.X = <Repeat <- s.N 1> s.F <Mu s.F e.X>>;
};

Fibonacci {
    e.X s.A s.B = e.X s.A s.B <+ s.A s.B>;
};
Output:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765

Relation

function fibonacci (n)
if n < 2 
set result = n
else
set f0 = 0
set f1 = 1
set k = 2
while k <= n
set result = f0 + f1
set f0 = f1
set f1 = result
set k = k + 1
end while
end if
end function

Retro

Recursive

: fib ( n-m ) dup [ 0 = ] [ 1 = ] bi or if; [ 1- fib ] sip [ 2 - fib ] do + ;

Iterative

: fib ( n-N )
  [ 0 1 ] dip [ over + swap ] times drop ;

REXX

With   210,000   numeric decimal digits,   this REXX program can handle Fibonacci numbers past one million.
[Generally speaking, some REXX interpreters can handle up to around eight million decimal digits.]

This version of the REXX program can also handle   negative   Fibonacci numbers.

/*REXX program calculates the  Nth  Fibonacci number,   N   can be  zero  or  negative. */
numeric digits 210000                            /*be able to handle ginormous numbers. */
parse  arg  x y .                                /*allow a  single number  or  a range. */
if x=='' | x==","  then do;  x=-40;  y=+40;  end /*No input?  Then use range -40 ──► +40*/
if y=='' | y==","  then y=x                      /*if only one number, display   fib(X).*/
w= max(length(x),  length(y) )                   /*W:  used for making formatted output.*/
fw= 10                                           /*Minimum maximum width. Sounds ka─razy*/
      do j=x  to y;          q= fib(j)           /*process all of the Fibonacci requests*/
      L= length(q)                               /*obtain the length (decimal digs) of Q*/
      fw= max(fw, L)                             /*fib number length, or the max so far.*/
      say 'Fibonacci('right(j,w)") = "  right(q,fw)                   /*right justify Q.*/
      if L>10  then  say    'Fibonacci('right(j, w)") has a length of"     L
      end   /*j*/                                /* [↑]  list a Fib. sequence of  x──►y */
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
fib:  procedure; parse arg n;        an= abs(n)  /*use  │n│   (the absolute value of N).*/
      a= 0;    b= 1;   if an<2  then return an   /*handle two special cases: zero & one.*/
                                                 /* [↓]   this method is non─recursive. */
         do k=2  to an;   $= a+b;   a= b;   b= $ /*sum  the numbers  up to   │n│        */
         end   /*k*/                             /* [↑]  (only positive Fibs nums used).*/
                                                 /* [↓]  an//2   [same as]   (an//2==1).*/
      if n>0 | an//2   then  return  $           /*Positive or even?   Then return sum. */
                             return -$           /*Negative and odd? Return negative sum*/
output   when using the default inputs:
Fibonacci(-40) =  -102334155
Fibonacci(-39) =    63245986
Fibonacci(-38) =   -39088169
Fibonacci(-37) =    24157817
Fibonacci(-36) =   -14930352
Fibonacci(-35) =     9227465
Fibonacci(-34) =    -5702887
Fibonacci(-33) =     3524578
Fibonacci(-32) =    -2178309
Fibonacci(-31) =     1346269
Fibonacci(-30) =     -832040
Fibonacci(-29) =      514229
Fibonacci(-28) =     -317811
Fibonacci(-27) =      196418
Fibonacci(-26) =     -121393
Fibonacci(-25) =       75025
Fibonacci(-24) =      -46368
Fibonacci(-23) =       28657
Fibonacci(-22) =      -17711
Fibonacci(-21) =       10946
Fibonacci(-20) =       -6765
Fibonacci(-19) =        4181
Fibonacci(-18) =       -2584
Fibonacci(-17) =        1597
Fibonacci(-16) =        -987
Fibonacci(-15) =         610
Fibonacci(-14) =        -377
Fibonacci(-13) =         233
Fibonacci(-12) =        -144
Fibonacci(-11) =          89
Fibonacci(-10) =         -55
Fibonacci( -9) =          34
Fibonacci( -8) =         -21
Fibonacci( -7) =          13
Fibonacci( -6) =          -8
Fibonacci( -5) =           5
Fibonacci( -4) =          -3
Fibonacci( -3) =           2
Fibonacci( -2) =          -1
Fibonacci( -1) =           1
Fibonacci(  0) =           0
Fibonacci(  1) =           1
Fibonacci(  2) =           1
Fibonacci(  3) =           2
Fibonacci(  4) =           3
Fibonacci(  5) =           5
Fibonacci(  6) =           8
Fibonacci(  7) =          13
Fibonacci(  8) =          21
Fibonacci(  9) =          34
Fibonacci( 10) =          55
Fibonacci( 11) =          89
Fibonacci( 12) =         144
Fibonacci( 13) =         233
Fibonacci( 14) =         377
Fibonacci( 15) =         610
Fibonacci( 16) =         987
Fibonacci( 17) =        1597
Fibonacci( 18) =        2584
Fibonacci( 19) =        4181
Fibonacci( 20) =        6765
Fibonacci( 21) =       10946
Fibonacci( 22) =       17711
Fibonacci( 23) =       28657
Fibonacci( 24) =       46368
Fibonacci( 25) =       75025
Fibonacci( 26) =      121393
Fibonacci( 27) =      196418
Fibonacci( 28) =      317811
Fibonacci( 29) =      514229
Fibonacci( 30) =      832040
Fibonacci( 31) =     1346269
Fibonacci( 32) =     2178309
Fibonacci( 33) =     3524578
Fibonacci( 34) =     5702887
Fibonacci( 35) =     9227465
Fibonacci( 36) =    14930352
Fibonacci( 37) =    24157817
Fibonacci( 38) =    39088169
Fibonacci( 39) =    63245986
Fibonacci( 40) =   102334155

output   when the following was used as input:   10000

Fibonacci(10000) =  3364476487643178326662161200510754331030214846068006390656476997468008144216666236815559551363373402558206533268083615937373479048386526826304089246305643188735454436955982749160660209988418393386465273130008883026923567361313511757929743785441375213052050434770160226475831890652789085515436615958298727968298751063120057542878345321551510387081829896979161312785626503319548714021428753269818796204693609787990035096230229102636813149319527563022783762844154036058440257211433496118002309120828704608892396232883546150577658327125254609359112820392528539343462090424524892940390
170623388899108584106518317336043747073790855263176432573399371287193758774689747992630583706574283016163740896917842637862421283525811282051637029808933209990570792006436742620238978311147005407499845925036063356093388383192338678305613643535189213327973290813373264265263398976392272340788292817795358057099369104917547080893184105614632233821746563732124822638309210329770164805472624384237486241145309381220656491403275108664339451751216152654536133311131404243685480510676584349352383695965342807176877532834823434555736671973139274627362910821067928078471803532913117677892465908993863545932789
452377767440619224033763867400402133034329749690202832814593341882681768389307200363479562311710310129195316979460763273758925353077255237594378843450406771555577905645044301664011946258097221672975861502696844314695203461493229110597067624326851599283470989128470674086200858713501626031207190317208609408129832158107728207635318662461127824553720853236530577595643007251774431505153960090516860322034916322264088524885243315805153484962243484829938090507048348244932745373262456775587908918719080366205800959474315005240253270974699531877072437682590741993963226598414749819360928522394503970716544
3156421328157688908058783183404917434556270520223564846495196112460268313970975069382648706613264507665074611512677522748621598642530711298441182622661057163515069260029861704945425047491378115154139941550671256271197133252763631939606902895650288268608362241082050562430701794976171121233066073310059947366875
Fibonacci(10000) has a length of  2090  decimal digits

Rhovas

Solutions support arbitrarily large numbers as Rhovas's Integer type is arbitrary-precision (Java BigInteger). Additional notes:

  • require num >= 0; asserts input range preconditions, throwing on negative numbers

Iterative

Standard iterative solution using a for loop:

  • range(1, num, :incl) creates an inclusive range (1 <= i <= num) for iteration.
    • The loop uses _ as the variable name since the value is unused.
func fibonacci(num: Integer): Integer {
    require num >= 0;
    var previous = 1;
    var current = 0;
    for (val _ in range(1, num, :incl)) {
        val next = current + previous;
        previous = current;
        current = next;
    }
    return current;
}

Recursive

Standard recursive solution using a pattern matching approach:

  • match without arguments is a conditional match, which works like if/else chains.
  • Rhovas doesn't perform tail-call optimization yet, hence why this solution isn't tail recursive.
func fibonacci(num: Integer): Integer {
    require num >= 0;
    match {
        num == 0: return 0;
        num == 1: return 1;
        else: return fibonacci(num - 1) + fibonacci(num - 2);
    }
}

Negatives

Standard solution using a pattern matching approach, delegating to an existing positiveFibonacci solution (as shown above). For negative fibonacci numbers, odd inputs return positive results while evens return negatives.

func fibonacci(num: Integer): Integer {
    match {
        num >= 0: return positiveFibonacci(num);
        num.mod(2) != 0: return positiveFibonacci(-num);
        else: return -positiveFibonacci(-num);
    }
}

Ring

give n
x = fib(n)
see n + " Fibonacci is : " + x

func fib nr if nr = 0 return 0 ok
            if nr = 1 return 1 ok 
            if nr > 1 return fib(nr-1) + fib(nr-2) ok

Rockstar

Iterative (minimized)

Fibonacci takes Number
  FNow is 0
  FNext is 1
  While FNow is less than Number
    Say FNow
    Put FNow into Temp
    Put FNow into FNext
    Put FNext plus Temp into FNext

Say Fibonacci taking 1000 (prints out highest number in Fibonacci sequence less than 1000)

Iterative (idiomatic)

Love takes Time
My love was addictions
Put my love into your heart
Build it up
Until my love is as strong as Time
Whisper my love
Put my love into a river
Put your heart into my love
Put it with a river into your heart


Shout; Love taking 1000 (years, years)

The semicolon and the comment (years, years) in this version are there only for poetic effect

Recursive

The Italian takes a lover, a kiss, a promise
love is population
hate is information
If a lover is love
Give back a kiss

If a lover is hate
Give back a promise

Knock a lover down
Put a promise with a kiss into my heart
Give back The Italian taking a lover, a promise, my heart

Listen to your heart
your mind is everything
your soul is opportunity
Whisper The Italian taking your heart, your mind, your soul

RPL

Works with: Halcyon Calc version 4.2.7

Iterative

≪ 0 1
   0 4 ROLL START 
      OVER + SWAP 
   NEXT SWAP DROP
≫ '→FIB' STO

≪ { } 0 20 FOR j j →FIB + NEXT ≫ EVAL

Recursive

IF DUP 2 > THEN 
     DUP 1 - →FIB 
     SWAP 2 - →FIB + 
   ELSE SIGN END 
≫ '→FIB' STO
Output:
1: { 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 }

Fast recursive

A much better recursive approach, based on the formulas: F(2k) = [2*F(k-1) + F(k)]*F(k) and F(2k+1) = F(k)² + F(k+1)²

IF DUP 2 ≤ THEN SIGN ELSE
     IF DUP 2 MOD
     THEN 1 - 2 / DUP →FIB SQ SWAP 1 + →FIB SQ +
     ELSE 2 / DUP →FIB DUP ROT 1 - →FIB 2 * + *
   END END
≫ '→FIB' STO

Ruby

Iterative

def fib(n)
  if n < 2
    n
  else
    prev, fib = 0, 1
    (n-1).times do
      prev, fib = fib, fib + prev
    end
    fib
  end
end

p (0..10).map { |i| fib(i) }

Output:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

Recursive

def fib(n, sequence=[1])
  return sequence.last if n == 0

  current_number, last_number = sequence.last(2)
  sequence << current_number + (last_number or 0)

  fib(n-1, sequence)
end

Recursive with Memoization

# Use the Hash#default_proc feature to
# lazily calculate the Fibonacci numbers.

fib = Hash.new do |f, n|
  f[n] = if n <= -2
           (-1)**(n + 1) * f[n.abs]
         elsif n <= 1
           n.abs
         else
           f[n - 1] + f[n - 2]
         end
end
# examples: fib[10] => 55, fib[-10] => (-55/1)

Matrix

require 'matrix'

# To understand why this matrix is useful for Fibonacci numbers, remember
# that the definition of Matrix.**2 for any Matrix[[a, b], [c, d]] is
# is [[a*a + b*c, a*b + b*d], [c*a + d*b, c*b + d*d]].  In other words, the
# lower right element is computing F(k - 2) + F(k - 1) every time M is multiplied
# by itself (it is perhaps easier to understand this by computing M**2, 3, etc, and
# watching the result march up the sequence of Fibonacci numbers).

M = Matrix[[0, 1], [1,1]]

# Matrix exponentiation algorithm to compute Fibonacci numbers.
# Let M be Matrix [[0, 1], [1, 1]].  Then, the lower right element of M**k is
# F(k + 1).  In other words, the lower right element of M is F(2) which is 1, and the
# lower right element of M**2 is F(3) which is 2, and the lower right element
# of M**3 is F(4) which is 3, etc.
#
# This is a good way to compute F(n) because the Ruby implementation of Matrix.**(n)
# uses O(log n) rather than O(n) matrix multiplications.  It works by squaring squares
# ((m**2)**2)... as far as possible
# and then multiplying that by by M**(the remaining number of times).  E.g., to compute
# M**19, compute partial = ((M**2)**2) = M**16, and then compute partial*(M**3) = M**19.
# That's only 5 matrix multiplications of M to compute M*19. 
def self.fib_matrix(n)
  return 0 if n <= 0 # F(0)
  return 1 if n == 1 # F(1)
  # To get F(n >= 2), compute M**(n - 1) and extract the lower right element.
  return CS::lower_right(M**(n - 1))
end

# Matrix utility to return
# the lower, right-hand element of a given matrix.
def self.lower_right matrix
  return nil if matrix.row_size == 0
  return matrix[matrix.row_size - 1, matrix.column_size - 1]
end

Generative

fib = Enumerator.new do |y|
  f0, f1 = 0, 1
  loop do
    y <<  f0
    f0, f1 = f1, f0 + f1
  end
end

Usage:

p fib.lazy.drop(8).next # => 21
Works with: Ruby version 1.9

"Fibers are primitives for implementing light weight cooperative concurrency in Ruby. Basically they are a means of creating code blocks that can be paused and resumed, much like threads. The main difference is that they are never preempted and that the scheduling must be done by the programmer and not the VM." [2]

fib = Fiber.new do
  a,b = 0,1
  loop do
    Fiber.yield a
    a,b = b,a+b
  end
end
9.times {puts fib.resume}

using a lambda

def fib_gen
    a, b = 1, 1
    lambda {ret, a, b = a, b, a+b; ret}
end
irb(main):034:0> fg = fib_gen
=> #<Proc:0xb7cdf750@(irb):22>
irb(main):035:0> 9.times { puts fg.call}
1
1
2
3
5
8
13
21
34
=> 9

Binet's Formula

def fib
    phi = (1 + Math.sqrt(5)) / 2
    ((phi**self - (-1 / phi)**self) / Math.sqrt(5)).to_i
end
1.9.3p125 :001 > def fib
1.9.3p125 :002?>   phi = (1 + Math.sqrt(5)) / 2
1.9.3p125 :003?>   ((phi**self - (-1 / phi)**self) / Math.sqrt(5)).to_i
1.9.3p125 :004?>   end
 => nil 
1.9.3p125 :005 > (0..10).map(&:fib)
 => [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

Rust

Iterative

fn main() {
    let mut prev = 0;
    // Rust needs this type hint for the checked_add method
    let mut curr = 1usize;

    while let Some(n) = curr.checked_add(prev) {
        prev = curr;
        curr = n;
        println!("{}", n);
    }
}

Recursive

use std::mem;
fn main() {
    fibonacci(0,1);
}

fn fibonacci(mut prev: usize, mut curr: usize) {
    mem::swap(&mut prev, &mut curr);
    if let Some(n) = curr.checked_add(prev) {
        println!("{}", n);
        fibonacci(prev, n);
    }
}

Recursive (with pattern matching)

fn fib(n: u32) -> u32 {
    match n {
        0 => 0,
        1 => 1,
        n => fib(n - 1) + fib(n - 2),
    }
}

Tail recursive (with pattern matching)

fn fib_tail_recursive(nth: usize) -> usize {
  fn fib_tail_iter(n: usize, prev_fib: usize, fib: usize) -> usize {
    match n {
      0 => prev_fib,
      n => fib_tail_iter(n - 1, fib, prev_fib + fib),
    }
  }
  fib_tail_iter(nth, 0, 1)
}

Analytic

fn main() {
    for num in fibonacci_sequence() {
        println!("{}", num);
    }
}

fn fibonacci_sequence() -> impl Iterator<Item = u64> {
    let sqrt_5 = 5.0f64.sqrt();
    let p = (1.0 + sqrt_5) / 2.0;
    let q = 1.0 / p;
    // The range is sufficient up to 70th Fibonacci number
    (0..1).chain((1..70).map(move |n| ((p.powi(n) + q.powi(n)) / sqrt_5 + 0.5) as u64))
}

Using an Iterator

Iterators are very idiomatic in rust, though they may be overkill for such a simple problem.

use std::mem;

struct Fib {
    prev: usize,
    curr: usize,
} 

impl Fib {
    fn new() -> Self {
        Fib {prev: 0, curr: 1}
    }
}

impl Iterator for Fib {
    type Item = usize;
    fn next(&mut self) -> Option<Self::Item>{
        mem::swap(&mut self.curr, &mut self.prev);
        self.curr.checked_add(self.prev).map(|n| { 
            self.curr = n;
            n
        })
    }
}

fn main() {
    for num in Fib::new() {
        println!("{}", num);
    }
}


Iterator "Successors"

fn main() {
    std::iter::successors(Some((1u128, 0)), |&(a, b)| a.checked_add(b).map(|s| (b, s)))
        .for_each(|(_, u)| println!("{}", u));
}


SAS

Iterative

This code builds a table fib holding the first few values of the Fibonacci sequence.

data fib;
    a=0;
    b=1;
    do n=0 to 20;
       f=a;
       output;
       a=b;
       b=f+a;
    end;
    keep n f;
run;

Naive recursive

This code provides a simple example of defining a function and using it recursively. One of the members of the sequence is written to the log.

options cmplib=work.f;

proc fcmp outlib=work.f.p;
    function fib(n);
    if n = 0 or n = 1
        then return(1);
        else return(fib(n - 2) + fib(n - 1));
    endsub;
run;

data _null_;
    x = fib(5);
    put 'fib(5) = ' x;
run;

Sather

The implementations use the arbitrary precision class INTI.

class MAIN is

  -- RECURSIVE --
  fibo(n :INTI):INTI
    pre n >= 0
  is
    if n < 2.inti then return n; end;
    return fibo(n - 2.inti) + fibo(n - 1.inti);
  end;

  -- ITERATIVE --
  fibo_iter(n :INTI):INTI
    pre n >= 0
  is
    n3w :INTI;

    if n < 2.inti then return n; end;
    last ::= 0.inti; this ::= 1.inti;
    loop (n - 1.inti).times!;
      n3w := last + this;
      last := this;
      this := n3w;
    end;   
    return this;
  end;

  main is
    loop i ::= 0.upto!(16);
      #OUT + fibo(i.inti) + " ";
      #OUT + fibo_iter(i.inti) + "\n";
    end;
  end;

end;

Scala

Recursive

def fib(i: Int): Int = i match {
  case 0 => 0
  case 1 => 1
  case _ => fib(i - 1) + fib(i - 2)
}

Lazy sequence

lazy val fib: LazyList[Int] = 0 #:: 1 #:: fib.zip(fib.tail).map { case (a, b) => a + b }

Tail recursive

import scala.annotation.tailrec
@tailrec
final def fib(x: Int, prev: BigInt = 0, next: BigInt = 1): BigInt = x match {
  case 0 => prev
  case _ => fib(x - 1, next, next + prev)
}

foldLeft

// Fibonacci using BigInt with LazyList.foldLeft optimized for GC (Scala v2.13 and above)
// Does not run out of memory for very large Fibonacci numbers
def fib(n: Int): BigInt = {

  def series(i: BigInt, j: BigInt): LazyList[BigInt] = i #:: series(j, i + j)

  series(1, 0).take(n).foldLeft(BigInt("0"))(_ + _)
}

// Small test
(0 to 13) foreach {n => print(fib(n).toString + " ")}

// result: 0 1 1 2 3 5 8 13 21 34 55 89 144 233

Iterator

val it: Iterator[Int] = Iterator.iterate((0, 1)) { case (a, b) => (b, a + b) }.map(_._1)

def fib(n: Int): Int = it.drop(n).next()

// example:
println(it.take(13).mkString(",")) // prints: 0,1,1,2,3,5,8,13,21,34,55,89,144

Scheme

Iterative

(define (fib-iter n)
  (do ((num 2 (+ num 1))
       (fib-prev 1 fib)
       (fib 1 (+ fib fib-prev)))
      ((>= num n) fib)))

Recursive

(define (fib-rec n)
  (if (< n 2)
      n
      (+ (fib-rec (- n 1))
         (fib-rec (- n 2)))))

This version is tail recursive:

(define (fib n)
  (let loop ((a 0) (b 1) (n n))
    (if (= n 0) a
        (loop b (+ a b) (- n 1)))))

Recursive Sequence Generator

Although the tail recursive version above is quite efficient, it only generates the final nth Fibonacci number and not the sequence up to that number without wasteful repeated calls to the procedure/function.

The following procedure generates the sequence of Fibonacci numbers using a simplified version of a lazy list/stream - since no memoization is requried, it just implements future values by using a zero parameter lambda "thunk" with a closure containing the last and the pre-calculated next value of the sequence; in this way it uses almost no memory during the sequence generation other than as required for the last and the next values of the sequence (note that the test procedure does not generate a linked list to contain the elements of the sequence to show, but rather displays each one by one in sequence):

(define (fib)
  (define (nxt lv nv) (cons nv (lambda () (nxt nv (+ lv nv)))))
  (cons 0 (lambda () (nxt 0 1))))

;;; test...
(define (show-stream-take n strm)
  (define (shw-nxt n strm) (begin (display (car strm))
                                  (if (> n 1) (begin (display " ") (shw-nxt (- n 1) ((cdr strm)))) (display ")"))))
  (begin (display "(") (shw-nxt n strm)))
(show-stream-take 30 (fib))
Output:
(0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229)

Dijkstra Algorithm

;;; Fibonacci numbers using Edsger Dijkstra's algorithm
;;; http://www.cs.utexas.edu/users/EWD/ewd06xx/EWD654.PDF

(define (fib n)
  (define (fib-aux a b p q count)
    (cond ((= count 0) b)
          ((even? count)
           (fib-aux a
                    b
                    (+ (* p p) (* q q))
                    (+ (* q q) (* 2 p q))
                    (/ count 2)))
          (else
           (fib-aux (+ (* b q) (* a q) (* a p))
                    (+ (* b p) (* a q))
                    p
                    q
                    (- count 1)))))
  (fib-aux 1 0 0 1 n))

Scilab

    clear
    n=46
    f1=0; f2=1
    printf("fibo(%d)=%d\n",0,f1)
    printf("fibo(%d)=%d\n",1,f2)
    for i=2:n
        f3=f1+f2
        printf("fibo(%d)=%d\n",i,f3)
        f1=f2
        f2=f3
    end
Output:
...
fibo(43)=433494437
fibo(44)=701408733
fibo(45)=1134903170
fibo(46)=1836311903

sed

#!/bin/sed -f

# First we need to convert each number into the right number of ticks 
# Start by marking digits
s/[0-9]/<&/g

# We have to do the digits manually.
s/0//g; s/1/|/g; s/2/||/g; s/3/|||/g; s/4/||||/g; s/5/|||||/g
s/6/||||||/g; s/7/|||||||/g; s/8/||||||||/g; s/9/|||||||||/g

# Multiply by ten for each digit from the front.
:tens
s/|</<||||||||||/g
t tens

# Done with digit markers
s/<//g

# Now the actual work.
:split
# Convert each stretch of n >= 2 ticks into two of n-1, with a mark between
s/|\(|\+\)/\1-\1/g
# Convert the previous mark and the first tick after it to a different mark
# giving us n-1+n-2 marks.
s/-|/+/g
# Jump back unless we're done.
t split
# Get rid of the pluses, we're done with them.
s/+//g

# Convert back to digits
:back
s/||||||||||/</g
s/<\([0-9]*\)$/<0\1/g
s/|||||||||/9/g;
s/|||||||||/9/g; s/||||||||/8/g; s/|||||||/7/g; s/||||||/6/g;
s/|||||/5/g; s/||||/4/g; s/|||/3/g; s/||/2/g; s/|/1/g;
s/</|/g
t back
s/^$/0/

Seed7

Recursive

const func integer: fib (in integer: number) is func
  result
    var integer: result is 1;
  begin
    if number > 2 then
      result := fib(pred(number)) + fib(number - 2);
    elsif number = 0 then
      result := 0;
    end if;
  end func;

Original source: [3]

Iterative

This funtion uses a bigInteger result:

const func bigInteger: fib (in integer: number) is func
  result
    var bigInteger: result is 1_;
  local
    var integer: i is 0;
    var bigInteger: a is 0_;
    var bigInteger: c is 0_;
  begin
    for i range 1 to pred(number) do
      c := a;
      a := result;
      result +:= c;
    end for;
  end func;

Original source: [4]

SequenceL

Recursive

fibonacci(n) := 
		n when n < 2
	else
		fibonacci(n - 1) + fibonacci(n - 2);

Based on: [5]

Tail Recursive

fibonacci(n) := fibonacciHelper(0, 1, n);
		
fibonacciHelper(prev, next, n) :=
		prev when n < 1
	else
		next when n = 1
	else
		fibonacciHelper(next, next + prev, n - 1);

Matrix

fibonacci(n) := fibonacciHelper([[1,0],[0,1]], n);

fibonacciHelper(M(2), n) := 
	let
		N := [[1,1],[1,0]];
	in
		M[1,1] when n <= 1
	else
		fibonacciHelper(matmul(M, N), n - 1);

matmul(A(2), B(2)) [i,j] := sum( A[i,all] * B[all,j] );

Based on the C# version: [6]

Using the SequenceL Matrix Multiply solution: [7]

SETL

$ Print out the first ten Fibonacci numbers
$ This uses Set Builder Notation, it roughly means
$ 'collect fib(n) forall n in {0,1,2,3,4,5,6,7,8,9,10}'
print({fib(n) : n in {0..10}});

$ Iterative Fibonacci function
proc fib(n);
    A := 0; B := 1; C := n;
    for i in {0..n} loop
        C := A + B;
        A := B;
        B := C;
    end loop;
    return C;
end proc;

Shen

(define fib
  0 -> 0
  1 -> 1
  N -> (+ (fib (+ N 1)) (fib (+ N 2))) 
       where (< N 0)
  N -> (+ (fib (- N 1)) (fib (- N 2))))

Sidef

Iterative

func fib_iter(n) {
    var (a, b) = (0, 1)
    { (a, b) = (b, a+b) } * n
    return a
}

Recursive

func fib_rec(n) {
    n < 2 ? n : (__FUNC__(n-1) + __FUNC__(n-2))
}

Recursive with memoization

func fib_mem (n) is cached {
    n < 2 ? n : (__FUNC__(n-1) + __FUNC__(n-2))
}

Closed-form

func fib_closed(n) {
    define S = (1.25.sqrt + 0.5)
    define T = (-S + 1)
    (S**n - T**n) / (-T + S) -> round
}

Built-in

say fib(12)    #=> 144

Simula

Straightforward iterative implementation.

INTEGER PROCEDURE fibonacci(n);
INTEGER n;
BEGIN
    INTEGER lo, hi, temp, i;
    lo := 0;
    hi := 1;
    FOR i := 1 STEP 1 UNTIL n - 1 DO
    BEGIN
        temp := hi;
        hi := hi + lo;
        lo := temp
    END;
    fibonacci := hi
END;

SkookumScript

Built-in

SkookumScript's Integer class has a fast built-in fibonnaci() method.

42.fibonacci

SkookumScript is designed to work in tandem with C++ and its strength is at the high-level stage-direction of things. So when confronted with benchmarking scripting systems it is genrally better to make a built-in call. Though in most practical cases this isn't necessary.

Recursive

Simple recursive method in same 42.fibonacci form as built-in form above.

// Assuming code is in Integer.fibonacci() method
() Integer
  [
  if this < 2 [this] else [[this - 1].fibonacci + [this - 2].fibonacci]
  ]

Recursive procedure in fibonacci(42) form.

// Assuming in fibonacci(n) procedure
(Integer n) Integer
  [
  if n < 2 [n] else [fibonacci(n - 1) + fibonacci(n - 2)]
  ]

Iterative

Iterative method in 42.fibonacci form.

// Assuming code is in Integer.fibonacci() method
() Integer
  [
  if this < 2
    [this]
  else
    [
    !prev: 1
    !next: 1
    2.to_pre this
      [
      !sum :  prev + next
      prev := next
      next := sum
      ]
      
    next
    ]    
  ]

Optimized iterative method in 42.fibonacci form. Though the best optimiation is to write it in C++ as with the built-in form that comes with SkookumScript.

// Bind : is faster than assignment :=
// loop is faster than to_pre (which uses a closure)
() Integer
  [
  if this < 2
    [this]
  else
    [
    !prev: 1
    !next: 1
    !sum
    !count: this - 2
    loop
      [
      if count = 0 [exit]
      count--
      sum  : prev + next
      prev : next
      next : sum
      ]
      
    next
    ]    
  ]

Slate

n@(Integer traits) fib
[
  n <= 0 ifTrue: [^ 0].
  n = 1 ifTrue: [^ 1].
  (n - 1) fib + (n - 2) fib
].

slate[15]> 10 fib = 55.
True

Smalltalk

Smalltalk already has a builtin fib in the Integer class (so I call them fibI and fibR in the code below, to not overwrite it). The integer algorithms below are all naive; there are faster ways to do it (see benchmark at the end). I gave the recursive version roughly 100Mb of stack. The analytical computation generates inexact results and fails for arguments somewhere above 1470 due to floating point overflow (with extended precision, the overflow appears a bit later).

iterative (slow):

Integer >> fibI
    |aNMinus1 an t|

    aNMinus1 := 1.
    an := 0.
    self timesRepeat:[
        t := an.
        an := an + aNMinus1 .
        aNMinus1 := t.
    ].
    ^ an

The recursive version although nice to read is the worst; it suffers from a huge stack requirement and a super poor performance (an anti-example for recursion):

Integer >> fibR
    (self > 1) ifTrue:[
        ^ (self - 1) fibR + (self - 2) fibR
    ].
    ^ self

analytic (fast, but inexact, and limited to small n below 1475 if we use double precision IEEE floats):

Integer >> fibBinet
    |phi rPhi|

    phi := Float phi.
    rPhi := 1 / phi.

    ^ (1 / 5 sqrt) * ((phi raisedTo:self) - (rPhi raisedTo:self))

using more bits in the exponent, we can compute larger fibs (up to 23599 with x86 extended precision floats), but still inexact:

Integer >> fibBinetFloatE
    |phi rPhi|

    phi := FloatE phi.
    rPhi := 1 / phi.

    ^ (1 / 5 sqrt) * ((phi raisedTo:self) - (rPhi raisedTo:self))
(10 to:1e6 byFactor:10) do:[:n |
  Transcript printCR:'----',n,'----'.
  Transcript printCR: n fibI.
  Transcript printCR: ([[n fibR] on:RecursionError do:['recursion']] valueWithTimeout:30 seconds) ? 'timeout'.
  Transcript printCR: n fibBinet.
  Transcript printCR: n fibBinetFloatE.
].

Transcript cr; showCR:'Timing:'; showCR:'------'.
[ 1000 fibI ] benchmark:'1000 fibI'.
[ 1000 fibR ] benchmark:'1000 fibR' timeLimit:30 seconds.
[ 1000 fibBinet ] benchmark:'1000 fibBinet'.
[ 1000 fibBinetFloatE] benchmark:'1000 fibBinetFloatE'.
[ 1000 fib ] benchmark:'1000 fib (builtin)'.

[ 10000 fibI ] benchmark:'10000 fibI'.
[ 10000 fib ] benchmark:'10000 fib (builtin)'.

[ 100000 fibI ] benchmark:'100000 fibI'.
[ 100000 fib ] benchmark:'100000 fib (builtin)'.

[ 1000000 fibI ] benchmark:'100000 fibI'.
[ 1000000 fib ] benchmark:'1000000 fib (builtin)'.
[ 2000000 fib ] benchmark:'2000000 fib (builtin)'.
[ 10000000 fib ] benchmark:'10000000 fib (builtin)'
Output:
----10----
55
55
55.0
54.99999999999
----100----
354224848179261915075
timeout
3.54224848179262E+020
3.54224848179263E+020
----1000----
43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875
timeout
4.34665576869373E+208
4.34665576869373E+208
----10000----
336447648764317832666216120051075433103021...050562430701794976171121233066073310059947366875 (2089 digits)
timeout
INF
3.364476487643176087E+2089
----100000----
259740693472217241661550340212759154148804853...653428746875 (20898 digits)
recursion
INF
INF
----1000000----
19532821287077577316320149475962563324435429965918733...2043347225419033684684301719893411568996526838242546875 (208987 digits)
recursion
INF
INF

Timing:
-------
1000 fibI: 94 µs (394736 cycles)
timeout after 30000ms
1000 fibBinet: 5500 ns (21746 cycles)
1000 fibBinetFloatE: 12 µs (43444 cycles)
1000 fib (builtin): 37 µs (130842 cycles)
10000 fibI: 2.44 ms (8775334 cycles)
10000 fib (builtin): 49 µs (175466 cycles)
100000 fibI: 156ms (563848550 cycles)
100000 fib (builtin): 1.66 ms (5970368 cycles)
1000000 fibI: 14.3s (51676292910 cycles)
1000000 fib (builtin): 71.95 ms (259023588 cycles)
2000000 fib (builtin): 229ms (827461038 cycles)
10000000 fib (builtin): 2.769s (9970686190 cycles)

SNOBOL4

Recursive

	define("fib(a)")	:(fib_end)
fib	fib = lt(a,2) a	:s(return)
	fib = fib(a - 1) + fib(a - 2)	:(return)
fib_end

while	a = trim(input)	:f(end)
	output = a " " fib(a)	:(while)
end

Tail-recursive

        define('trfib(n,a,b)') :(trfib_end)
trfib   trfib = eq(n,0) a :s(return)
        trfib = trfib(n - 1, a + b, a) :(return)
trfib_end

Iterative

        define('ifib(n)f1,f2') :(ifib_end)
ifib    ifib = le(n,2) 1 :s(return)
        f1 = 1; f2 = 1
if1     ifib = gt(n,2) f1 + f2 :f(return)
        f1 = f2; f2 = ifib; n = n - 1 :(if1)
ifib_end

Analytic

Works with: Macro Spitbol
Works with: CSnobol

Note: Snobol4+ lacks built-in sqrt( ) function.

        define('afib(n)s5') :(afib_end)
afib    s5 = sqrt(5)
        afib = (((1 + s5) / 2) ^ n - ((1 - s5) / 2) ^ n) / s5
        afib = convert(afib,'integer') :(return)
afib_end

Test and display all, Fib 1 .. 10

loop    i = lt(i,10) i + 1 :f(show)
        s1 = s1 fib(i) ' ' ; s2 = s2 trfib(i,0,1) ' '
        s3 = s3 ifib(i) ' '; s4 = s4 afib(i) ' ' :(loop)
show    output = s1; output = s2; output = s3; output = s4
end

Output:

1 1 2 3 5 8 13 21 34 55
1 1 2 3 5 8 13 21 34 55
1 1 2 3 5 8 13 21 34 55
1 1 2 3 5 8 13 21 34 55

SNUSP

This is modular SNUSP (which introduces @ and # for threading).

Iterative

 @!\+++++++++#  /<<+>+>-\       
fib\==>>+<<?!/>!\      ?/\      
  #<</?\!>/@>\?-<<</@>/@>/>+<-\ 
     \-/  \       !\ !\ !\   ?/#

Recursive

             /========\    />>+<<-\  />+<-\
fib==!/?!\-?!\->+>+<<?/>>-@\=====?/<@\===?/<#
      |  #+==/     fib(n-2)|+fib(n-1)|
      \=====recursion======/!========/

Spin

Iterative

Works with: BST/BSTC
Works with: FastSpin/FlexSpin
Works with: HomeSpun
Works with: OpenSpin
con
  _clkmode = xtal1 + pll16x
  _clkfreq = 80_000_000
 
obj
  ser : "FullDuplexSerial.spin"
 
pub main | i
  ser.start(31, 30, 0, 115200)

  repeat i from 0 to 10
    ser.dec(fib(i))
    ser.tx(32)

  waitcnt(_clkfreq + cnt)
  ser.stop
  cogstop(0)

pub fib(i) : b | a 
  b := a := 1 
  repeat i 
    a := b + (b := a)
Output:
1 1 2 3 5 8 13 21 34 55 89

SPL

Analytic

fibo(n)=
  s5 = #.sqrt(5)
  <= (((1+s5)/2)^n-((1-s5)/2)^n)/s5
.

Iterative

fibo(n)=
  ? n<2, <= n
  f2 = 0
  f1 = 1
  > i, 2..n
    f = f1+f2
    f2 = f1
    f1 = f
  <
  <= f
.

Recursive

fibo(n)=
  ? n<2, <= n
  <= fibo(n-1)+fibo(n-2)
.

SQL

Analytic

As a running sum:

select round ( exp ( sum (ln ( ( 1 + sqrt( 5 ) ) / 2)
        ) over ( order by level ) ) / sqrt( 5 ) ) fibo
from dual
connect by level <= 10;
       FIB
----------
         1
         1
         2
         3
         5
         8
        13
        21
        34
        55

10 rows selected.

As a power:

select round ( power( ( 1 + sqrt( 5 ) ) / 2, level ) / sqrt( 5 ) ) fib
from dual
connect by level <= 10;
       FIB
----------
         1
         1
         2
         3
         5
         8
        13
        21
        34
        55

10 rows selected.

Recursive

Works with: Oracle

Oracle 12c required

SQL> with fib(e,f) as (select 1, 1 from dual union all select e+f,e from fib where e <= 55) select f from fib;

         F
----------
         1
         1
         2
         3
         5
         8
        13
        21
        34
        55

10 rows selected.
Works with: PostgreSQL
CREATE FUNCTION fib(n int) RETURNS numeric AS $$
    -- This recursive with generates endless list of Fibonacci numbers.
    WITH RECURSIVE fibonacci(current, previous) AS (
        -- Initialize the current with 0, so the first value will be 0.
        -- The previous value is set to 1, because its only goal is not
        -- special casing the zero case, and providing 1 as the second
        -- number in the sequence.
        --
        -- The numbers end with dots to make them numeric type in
        -- Postgres. Numeric type has almost arbitrary precision
        -- (technically just 131,072 digits, but that's good enough for
        -- most purposes, including calculating huge Fibonacci numbers)
        SELECT 0., 1.
    UNION ALL
        -- To generate Fibonacci number, we need to add together two
        -- previous Fibonacci numbers. Current number is saved in order
        -- to be accessed in the next iteration of recursive function.
        SELECT previous + current, current FROM fibonacci
    )
    -- The user is only interested in current number, not previous.
    SELECT current FROM fibonacci
    -- We only need one number, so limit to 1
    LIMIT 1
    -- Offset the query by the requested argument to get the correct
    -- position in the list.
    OFFSET n
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT IMMUTABLE;

SSEM

Calculates the tenth Fibonacci number. To calculate the nth, change the initial value of the counter to n-1 (subject to the restriction that the answer must be small enough to fit in a signed 32-bit integer, the SSEM's only data type). The algorithm is basically straightforward, but the absence of an Add instruction makes the implementation a little more complicated than it would otherwise be.

10101000000000100000000000000000    0. -21 to c    acc = -n
01101000000001100000000000000000    1. c   to 22   temp = acc
00101000000001010000000000000000    2. Sub. 20     acc -= m
10101000000001100000000000000000    3. c   to 21   n = acc
10101000000000100000000000000000    4. -21 to c    acc = -n
10101000000001100000000000000000    5. c   to 21   n = acc
01101000000000100000000000000000    6. -22 to c    acc = -temp
00101000000001100000000000000000    7. c   to 20   m = acc
11101000000000100000000000000000    8. -23 to c    acc = -count
00011000000001010000000000000000    9. Sub. 24     acc -= -1
00000000000000110000000000000000   10. Test        skip next if acc<0
10011000000000000000000000000000   11. 25  to CI   goto (15 + 1)
11101000000001100000000000000000   12. c   to 23   count = acc
11101000000000100000000000000000   13. -23 to c    acc = -count
11101000000001100000000000000000   14. c   to 23   count = acc
00011000000000000000000000000000   15. 24  to CI   goto (-1 + 1)
10101000000000100000000000000000   16. -21 to c    acc = -n
10101000000001100000000000000000   17. c   to 21   n = acc
10101000000000100000000000000000   18. -21 to c    acc = -n
00000000000001110000000000000000   19. Stop
00000000000000000000000000000000   20. 0           var m = 0
10000000000000000000000000000000   21. 1           var n = 1
00000000000000000000000000000000   22. 0           var temp = 0
10010000000000000000000000000000   23. 9           var count = 9
11111111111111111111111111111111   24. -1          const -1
11110000000000000000000000000000   25. 15          const 15

Stata

program fib
args n
clear
qui set obs `n'
qui gen a=1
qui replace a=a[_n-1]+a[_n-2] in 3/l
end

An implementation using dyngen.

program fib
args n
clear
qui set obs `n'
qui gen a=.
dyngen {
	update a=a[_n-1]+a[_n-2], missval(1)
}
end

fib 10
list

Output

     +----+
     |  a |
     |----|
  1. |  1 |
  2. |  1 |
  3. |  2 |
  4. |  3 |
  5. |  5 |
     |----|
  6. |  8 |
  7. | 13 |
  8. | 21 |
  9. | 34 |
 10. | 55 |
     +----+

Mata

. mata
: function fib(n) {
        return((((1+sqrt(5))/2):^n-((1-sqrt(5))/2):^n)/sqrt(5))
}

: fib(0..10)
        1    2    3    4    5    6    7    8    9   10   11
    +--------------------------------------------------------+
  1 |   0    1    1    2    3    5    8   13   21   34   55  |
    +--------------------------------------------------------+

: end

StreamIt

void->int feedbackloop Fib {
    join roundrobin(0,1);
    body in->int filter {
        work pop 1 push 1 peek 2 { push(peek(0) + peek(1)); pop(); }
    };
    loop Identity<int>;
    split duplicate;
    enqueue(0);
    enqueue(1);
}

SuperCollider

Recursive

nth fibonacci term for positive n

f = { |n| if(n < 2) { n } { f.(n-1) + f.(n-2) } };
(0..20).collect(f)

nth fibonacci term for positive and negative n.

f = { |n| var u = neg(sign(n)); if(abs(n) < 2) { n } { f.(2 * u + n) + f.(u + n) } };
(-20..20).collect(f)

Analytic

(
	f = { |n|
		var sqrt5 = sqrt(5);
		var p = (1 + sqrt5) / 2;
		var q = reciprocal(p);
		((p ** n) + (q ** n) / sqrt5 + 0.5).trunc
	};
	(0..20).collect(f)
)

Iterative

f = { |n| var a = [1, 1]; n.do { a = a.addFirst(a[0] + a[1]) }; a.reverse };
f.(18)

Swift

Analytic

import Cocoa

func fibonacci(n: Int) -> Int {
    let square_root_of_5 = sqrt(5.0)
    let p = (1 + square_root_of_5) / 2
    let q = 1 / p
    return Int((pow(p,CDouble(n)) + pow(q,CDouble(n))) / square_root_of_5 + 0.5)
}

for i in 1...30 {
    println(fibonacci(i))
}

Iterative

func fibonacci(n: Int) -> Int {
    if n < 2 {
        return n
    }
    var fibPrev = 1
    var fib = 1
    for num in 2...n {
        (fibPrev, fib) = (fib, fib + fibPrev)
    }
    return fib
}

Sequence:

func fibonacci() -> SequenceOf<UInt> {
  return SequenceOf {() -> GeneratorOf<UInt> in
    var window: (UInt, UInt, UInt) = (0, 0, 1)
    return GeneratorOf {
      window = (window.1, window.2, window.1 + window.2)
      return window.0
    }
  }
}

Recursive

func fibonacci(n: Int) -> Int {
    if n < 2 {
        return n
    } else {
        return fibonacci(n-1) + fibonacci(n-2)
    }
}

println(fibonacci(30))

Tailspin

Recursive simple

The simplest exponential-time recursive algorithm only handling positive N. Note that the "#" is the tailspin internal recursion which sends the value to the matchers. In this case where there is no initial block and no templates state, we could equivalently write the templates name "nthFibonacci" in place of the "#" to do a normal recursion.

templates nthFibonacci
  when <=0|=1> do $ !
  otherwise ($ - 1 -> #) + ($ - 2 -> #) !
end nthFibonacci

Iterative, mutable state

We could use the templates internal mutable state, still only positive N.

templates nthFibonacci
  @: {n0: 0"1", n1: 1"1"};
  1..$ -> @: {n0: $@.n1, n1: $@.n0 + $@.n1};
  $@.n0!
end nthFibonacci

To handle negatives, we can keep track of the sign and send it to the matchers.

templates nthFibonacci
  @: {n0: 0"1", n1: 1"1"};
  def sign: $ -> \(<0..> 1! <> -1!\);
  1..$*$sign -> $sign -> #
  $@.n0!
  <=1>
    @: {n0: $@.n1, n1: $@.n0 + $@.n1};
  <=-1>
    @: {n0: $@.n1 - $@.n0, n1: $@.n0};
end nthFibonacci

State machine

Instead of mutating state, we could just recurse internally on a state structure.

templates nthFibonacci
  { N: ($)"1", n0: 0"1", n1: 1"1" } -> #
  when <{ N: <=0"1"> }> do
    $.n0 !
  when <{ N: <1"1"..>}> do
    { N: $.N - 1"1", n0: $.n1, n1: $.n0 + $.n1} -> #
  otherwise
    { N: $.N + 1"1", n1: $.n0, n0: $.n1 - $.n0} -> #
end nthFibonacci
 
8 -> nthFibonacci -> '$;
' -> !OUT::write
-5 -> nthFibonacci -> '$;
' -> !OUT::write
-6 -> nthFibonacci -> '$;
' -> !OUT::write
Output:
21"1"
5"1"
-8"1"

Tcl

Simple Version

These simple versions do not handle negative numbers -- they will return N for N < 2

Iterative

Translation of: Perl
proc fibiter n {
    if {$n < 2} {return $n}
    set prev 1
    set fib 1
    for {set i 2} {$i < $n} {incr i} {
        lassign [list $fib [incr fib $prev]] prev fib
    }
    return $fib
}

Recursive

proc fib {n} {
    if {$n < 2} then {expr {$n}} else {expr {[fib [expr {$n-1}]]+[fib [expr {$n-2}]]} }
}

The following

Works with: Tcl version 8.5

: defining a procedure in the ::tcl::mathfunc namespace allows that proc to be used as a function in expr expressions.

proc tcl::mathfunc::fib {n} {
    if { $n < 2 } {
        return $n
    } else {
        return [expr {fib($n-1) + fib($n-2)}]
    }
}

# or, more tersely

proc tcl::mathfunc::fib {n} {expr {$n<2 ? $n : fib($n-1) + fib($n-2)}}

E.g.:

expr {fib(7)} ;# ==> 13

namespace path tcl::mathfunc #; or, interp alias {} fib {} tcl::mathfunc::fib
fib 7 ;# ==> 13

Tail-Recursive

In Tcl 8.6 a tailcall function is available to permit writing tail-recursive functions in Tcl. This makes deeply recursive functions practical. The availability of large integers also means no truncation of larger numbers.

proc fib-tailrec {n} {
    proc fib:inner {a b n} {
        if {$n < 1} {
            return $a
        } elseif {$n == 1} {
            return $b
        } else {
            tailcall fib:inner $b [expr {$a + $b}] [expr {$n - 1}]
        }
    }
    return [fib:inner 0 1 $n]
}
% fib-tailrec 100
354224848179261915075

Handling Negative Numbers

Iterative

proc fibiter n {
    if {$n < 0} {
        set n [expr {abs($n)}]
        set sign [expr {-1**($n+1)}]
    } else {
        set sign 1
    }
    if {$n < 2} {return $n}
    set prev 1
    set fib 1
    for {set i 2} {$i < $n} {incr i} {
        lassign [list $fib [incr fib $prev]] prev fib
    }
    return [expr {$sign * $fib}]
}
fibiter -5 ;# ==> 5
fibiter -6 ;# ==> -8

Recursive

proc tcl::mathfunc::fib {n} {expr {$n<-1 ? -1**($n+1) * fib(abs($n)) : $n<2 ? $n : fib($n-1) + fib($n-2)}}
expr {fib(-5)} ;# ==> 5
expr {fib(-6)} ;# ==> -8

For the Mathematically Inclined

This works up to , after which the limited precision of IEEE double precision floating point arithmetic starts to show.

Works with: Tcl version 8.5
proc fib n {expr {round((.5 + .5*sqrt(5)) ** $n / sqrt(5))}}

Tern

Recursive

func fib(n) {
   if (n < 2) {
      return 1;
   }
   return fib(n - 1) + fib(n - 2);
}

Coroutine

func fib(n) {
   let a = 1;
   let b = 2;
   
   until(n-- <= 0) {
      yield a;
      (a, b) = (b, a + b);
   }
}

TI SR-56

Texas Instruments SR-56 Program Listing for "Fibonacci Sequence"
Display Key Display Key Display Key Display Key
00 33 STO 25 50 75
01 00 0 26 51 76
02 01 1 27 52 77
03 33 STO 28 53 78
04 01 1 29 54 79
05 00 0 30 55 80
06 84 + 31 56 81
07 39 *EXC 32 57 82
08 01 1 33 58 83
09 94 = 34 59 84
10 27 *dsz 35 60 85
11 00 0 36 61 86
12 06 6 37 62 87
13 41 R/S 38 63 88
14 22 GTO 39 64 89
15 00 0 40 65 90
16 06 6 41 66 91
17 42 67 92
18 43 68 93
19 44 69 94
20 45 70 95
21 46 71 96
22 47 72 97
23 48 73 98
24 49 74 99

Asterisk denotes 2nd function key.

Register allocation
0: Nth term requested 1: Last term 2: Unused 3: Unused 4: Unused
5: Unused 6: Unused 7: Unused 8: Unused 9: Unused

Annotated listing:

STO 0        // Nth term requested := User input
1 STO 1      // Last term := 1
0            // Initial value: 0
+ *EXC 1 =   // Calculate next term.
*dsz 0 6     // Loop while R0 positive
R/S          // Done, show answer
GTO 0 6      // If user hits R/S calculate next term

Usage:

At the keypad enter a number N, then press RST R/S to calculate and display the Nth Fibonacci number. R/S for the following numbers.

Input:
1 RST R/S
Output:
1
Input:
2 RST R/S
Output:
1
Input:
3 RST R/S
Output:
2
Input:
10 RST R/S
Output:
55
R/S -> 89
R/S -> 144

TI-57

Step Function Comment
00 STO 0 R0 = n
01 C.t R7 = 0
02 1 Display = 1
03 INV SUM 1 R0 -= 1
04 Lbl 1 loop
05 +
06 x⮂t Swap Display with R7
07 = Display += R7
08 Dsz R0 -= 1
09 GTO 1 until R0 == 0
10 R/S Stop
11 RST Go back to step 0
10  RST R/S
Output:
55.

TSE SAL

// library: math: get: series: fibonacci <description></description> <version control></version control> <version>1.0.0.0.3</version> <version control></version control> (filenamemacro=getmasfi.s) [<Program>] [<Research>] [kn, ri, su, 20-01-2013 22:04:02]
INTEGER PROC FNMathGetSeriesFibonacciI( INTEGER  nI )
 //
 // Method:
 //
 // 1. Take the sum of the last 2 terms
 //
 // 2. Let the sum be the last term
 //    and goto step 1
 //
 INTEGER I = 0
 INTEGER minI = 1
 INTEGER maxI = nI
 INTEGER term1I = 0
 INTEGER term2I = 1
 INTEGER term3I = 0
 //
 FOR I = minI TO maxI
  //
  // make value 3 equal to sum of two previous values 1 and 2
  //
  term3I = term1I + term2I
  //
  // make value 1 equal to next value 2
  //
  term1I = term2I
  //
  // make value 2 equal to next value 3
  //
  term2I = term3I
  //
  ENDFOR
  //
 RETURN( term3I )
 //
END

PROC Main()
 STRING s1[255] = "3"
 REPEAT
  IF ( NOT ( Ask( " = ", s1, _EDIT_HISTORY_ ) ) AND ( Length( s1 ) > 0 ) ) RETURN() ENDIF
  Warn( FNMathGetSeriesFibonacciI( Val( s1 ) ) ) // gives e.g. 3
 UNTIL FALSE
END

Turing

% Recursive
function fibb (n: int) : int
    if n < 2 then
        result n
    else
        result fibb (n-1) + fibb (n-2)
    end if
end fibb

% Iterative
function ifibb (n: int) : int
    var a := 0  
    var b := 1
    for : 1 .. n
        a := a + b
        b := a - b
    end for
    result a
end ifibb

for i : 0 .. 10
    put fibb (i) : 4, ifibb (i) : 4
end for

Output:

   0   0
   1   1
   1   1
   2   2
   3   3
   5   5
   8   8
  13  13
  21  21
  34  34
  55  55

TUSCRIPT

$$ MODE TUSCRIPT
ASK "What fibionacci number do you want?": searchfib=""
IF (searchfib!='digits') STOP
Loop n=0,{searchfib}
 IF (n==0) THEN
   fib=fiba=n
 ELSEIF (n==1) THEN
   fib=fibb=n
 ELSE
   fib=fiba+fibb, fiba=fibb, fibb=fib
 ENDIF
 IF (n!=searchfib) CYCLE
 PRINT "fibionacci number ",n,"=",fib
ENDLOOP

Output:

What fibionacci number do you want? >12
fibionacci number 12=144

Output:

What fibionacci number do you want? >31
fibionacci number 31=1346269 

Output:

What fibionacci number do you want? >46
fibionacci 46=1836311903

Uiua

Works with: Uiua version 0.10.0-dev.1

Simple recursive example with memoisation.

F ← |1 memo⟨+⊃(F-1)(F-2)|∘⟩<2.
F ⇡20

UNIX Shell

Works with: bash version 3
#!/bin/bash

a=0
b=1
max=$1

for (( n=1; "$n" <= "$max"; $((n++)) ))
do
  a=$(($a + $b))
  echo "F($n): $a"
  b=$(($a - $b))
done

Recursive:

Works with: bash version 3
fib() {
  local n=$1
  [ $n -lt 2 ] && echo -n $n || echo -n $(( $( fib $(( n - 1 )) ) + $( fib $(( n - 2 )) ) ))
}

UnixPipes

This example is incorrect. Please fix the code and remove this message.

Details: There is a race between parallel commands. tee last might open and truncate the file before cat last opens it. Then cat last pipes the empty file to xargs, and expr reports a syntax error, and the script hangs forever.

echo 1 |tee last fib ; tail -f fib | while read x
do
   cat last | tee -a fib | xargs -n 1 expr $x + |tee last
done

Ursa

Translation of: Python

Iterative

def fibIter (int n)
	if (< n 2)
		return n
	end if
	decl int fib fibPrev num
	set fib (set fibPrev 1)
	for (set num 2) (< num n) (inc num)
		set fib (+ fib fibPrev)
		set fibPrev (- fib fibPrev)
	end for
	return fib
end

Ursala

All three methods are shown here, and all have unlimited precision.

#import std
#import nat

iterative_fib = ~&/(0,1); ~&r->ll ^|\predecessor ^/~&r sum

recursive_fib = {0,1}^?<a/~&a sum^|W/~& predecessor^~/~& predecessor

analytical_fib =

%np+ -+
   mp..round; ..mp2str; sep`+; ^CNC/~&hh take^\~&htt %np@t,
   (mp..div^|\~& mp..sub+ ~~ @rlX mp..pow_ui)^lrlPGrrPX/~& -+
      ^\~& ^(~&,mp..sub/1.E0)+ mp..div\2.E0+ mp..add/1.E0,
      mp..sqrt+ ..grow/5.E0+-+-

The analytical method uses arbitrary precision floating point arithmetic from the mpfr library and then converts the result to a natural number. Sufficient precision for an exact result is always chosen based on the argument. This test program computes the first twenty Fibonacci numbers by all three methods.

#cast %nLL

examples = <.iterative_fib,recursive_fib,analytical_fib>* iota20

output:

<
   <0,0,0>,
   <1,1,1>,
   <1,1,1>,
   <2,2,2>,
   <3,3,3>,
   <5,5,5>,
   <8,8,8>,
   <13,13,13>,
   <21,21,21>,
   <34,34,34>,
   <55,55,55>,
   <89,89,89>,
   <144,144,144>,
   <233,233,233>,
   <377,377,377>,
   <610,610,610>,
   <987,987,987>,
   <1597,1597,1597>,
   <2584,2584,2584>,
   <4181,4181,4181>>

V

Generate n'th fib by using binary recursion

[fib
   [small?] []
     [pred dup pred]
     [+]
   binrec].

Vala

Recursive

Using int, but could easily replace with double, long, ulong, etc.

int fibRec(int n){
	if (n < 2)
		return n;
	else
		return fibRec(n - 1) + fibRec(n - 2);
}

Iterative

Using int, but could easily replace with double, long, ulong, etc.

int fibIter(int n){
	if (n < 2)
		return n;
	
	int last = 0;
	int cur = 1;
	int next;
	
	for (int i = 1; i < n; ++i){
		next = last + cur;
		last = cur;
		cur = next;
	}
	
	return cur;
}

VAX Assembly

                               0000  0000     1 .entry	main,0
                            7E 7CFD  0002     2 	clro	-(sp)			;result buffer
                            5E   DD  0005     3 	pushl	sp			;pointer to buffer
                            10   DD  0007     4 	pushl	#16			;descriptor: len of buffer
                       5B   5E   D0  0009     5 	movl	sp, r11			;-> descriptor
                                     000C     6 
                       7E   01   7D  000C     7 	movq	#1, -(sp)		;init 0,1
                                     000F     8 loop:
               7E   6E   04 AE   C1  000F     9 	addl3	4(sp), (sp), -(sp)	;next element on stack
                            17   1D  0014    10 	bvs	ret			;vs - overflow set, exit
                                     0016    11 
                            5B   DD  0016    12 	pushl	r11			;-> descriptor by ref
                         04 AE   DF  0018    13 	pushal	4(sp)			;-> fib on stack by ref
              00000000'GF   02   FB  001B    14 	calls	#2, g^ots$cvt_l_ti	;convert integer to string
                            5B   DD  0022    15 	pushl	r11			;
              00000000'GF   01   FB  0024    16 	calls	#1, g^lib$put_output	;show result
                            E2   11  002B    17 	brb	loop
                                     002D    18 ret:
                                 04  002D    19 	ret
                                     002E    20 .end	main
$ run fib
...
        14930352
        24157817
        39088169
        63245986
       102334155
       165580141
       267914296
       433494437
       701408733
      1134903170
      1836311903
$

Vedit macro language

Iterative

Calculate fibonacci(#1). Negative values return 0.

:FIBONACCI:
#11 = 0
#12 = 1
Repeat(#1) {
    #10 = #11 + #12
    #11 = #12
    #12 = #10
}
Return(#11)

Unlimited precision

// Fibonacci, unlimited precision.
//  input: #1 = n
//  return: fibonacci(n) in text register 10
//
:fibo_unlimited:
if (#1 < 2) {
    Num_Str(#1, 10)
    return
} else {
    Buf_Switch(Buf_Free)
    IC('0') IN
    IC('1') IN
    #10 = #1
    While (#10 > 1) {
        #12 = 0			// carry out
	#15 = 1			// column (ones, tens, hundreds...)
	Repeat (ALL) {		// Sum all columns
	    Line(-1)			// n-1
	    Goto_col(#15)
	    if (At_EOL) {		// all digits added
		break
	    }
	    #11 = Cur_Char - '0' + #12	// digit of (n-1) + carry
	    Line(-1)			// n-2
	    Goto_Col(#15)
	    if (!At_EOL) {		// may contain fewer digits than n-1
		#11 += Cur_Char - '0'
	    }
	    Goto_Line(3)		// sum
	    EOL
	    #12 = #11 / 10		// carry out
	    Ins_Char((#11 % 10) + '0')
	    #15++			// next column
	}
	if (#12) {			
	    Goto_Line(3)
	    EOL
	    Ins_Char(#12 + '0')		// any extra digit from carry
        }
	BOF
	Del_Line(1)			// Next n
	Line(1) EOL
	Ins_Newline
	#10--
    }
    Goto_Line(2)		// Results on line 2
}
// Copy the results to text register 10 in reverse order
Reg_Empty(10)
While(!At_EOL) {
    Reg_Copy_Block(10, CP, CP+1, INSERT)
    Char()
}
Buf_Quit(OK)
return

Test:

#1 = Get_Num("n: ", STATLINE)
Ins_Text("fibonacci(") Num_Ins(#1, LEFT+NOCR) Ins_Text(") = ")
Call("fibo_unlimited")
Reg_Ins(10) IN
return
Output:
fibonacci(1000) = 43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875

V (Vlang)

Update V (Vlang) to version 0.2.2

Iterative

fn fib_iter(n int) int {
    if n < 2 {
      return n
    }

    mut prev, mut fib := 0, 1
    for _ in 0..(n - 1){
        prev, fib = fib, prev + fib
    }
    return fib
}

fn main() {
    for val in 0..11 {
        println('fibonacci(${val:2d}) = ${fib_iter(val):3d}')
    }
}

Recursive

fn fib_rec(n int) int {
    if n < 2 {
      return n
    }
    return fib_rec(n - 2) + fib_rec(n - 1)
}

fn main() {
    for val in 0..11 {
        println('fibonacci(${val:2d}) = ${fib_rec(val):3d}')
    }
}
Output:
fibonacci( 0) =   0
fibonacci( 1) =   1
fibonacci( 2) =   1
fibonacci( 3) =   2
fibonacci( 4) =   3
fibonacci( 5) =   5
fibonacci( 6) =   8
fibonacci( 7) =  13
fibonacci( 8) =  21
fibonacci( 9) =  34
fibonacci(10) =  55

Wart

Recursive, all at once

def (fib n)
  if (n < 2)
    n
    (+ (fib n-1) (fib n-2))

Recursive, using cases

def (fib n)
  (+ (fib n-1) (fib n-2))

def (fib n) :case (n < 2)
  n

Recursive, using memoization

def (fib n saved)
  # all args in Wart are optional, and we expect callers to not provide `saved`
  default saved :to (table 0 0 1 1)  # pre-populate base cases
  default saved.n :to
    (+ (fib n-1 saved) (fib n-2 saved))
  saved.n

WDTE

Memoized Recursive

let memo fib n => n { > 1 => + (fib (- n 1)) (fib (- n 2)) };

Iterative

let s => import 'stream';
let a => import 'arrays';

let fib n => (
	let reducer p n => [a.at p 1; + (a.at p 0) (a.at p 1)];
	s.range 1 n
	-> s.reduce [0; 1] reducer
	-> a.at 1
	;
);

WebAssembly

(func $fibonacci_nth (param $n i32) (result i32)

    ;;Declare some local registers
    (local $i i32)
    (local $a i32)
    (local $b i32)
 
    ;;Handle first 2 numbers as special cases
    (if (i32.eq (get_local $n) (i32.const 0))
        (return (i32.const 0))
    )
    (if (i32.eq (get_local $n) (i32.const 1))
        (return (i32.const 1))
    )
 
    ;;Initialize first two values
    (set_local $i (i32.const 1))
    (set_local $a (i32.const 0))
    (set_local $b (i32.const 1))
 
    (block 
        (loop 
            ;;Add two previous numbers and store the result
            local.get $a
            local.get $b
            i32.add 
            (set_local $a (get_local $b))
            set_local $b
 
            ;;Increment counter i by one
            (set_local $i                 
                (i32.add 
                    (get_local $i)
                    (i32.const 1)
                )
            )
 
            ;;Check if loop is done
            (br_if 1 (i32.ge_u (get_local $i) (get_local $n)))
            (br 0)
        )
    )
 
    ;;The result is stored in b, so push that to the stack
    get_local $b
)

Whitespace

Iterative

This program generates Fibonacci numbers until it is forced to terminate.

It was generated from the following pseudo-Assembly.

push 0
push 1

0:
    swap
    dup
    onum
    push 10
    ochr
    copy 1
    add
    jump 0
Output:
$ wspace fib.ws | head -n 6
0
1
1
2
3
5

Recursive

This program takes a number n on standard input and outputs the nth member of the Fibonacci sequence.

; Read n.
push 0
dup
inum
load

; Call fib(n), ouput the result and a newline, then exit.
call 0
onum
push 10
ochr
exit

0:
    dup
    push 2
    sub
    jn 1   ; Return if n < 2.
    dup
    push 1
    sub
    call 0 ; Call fib(n - 1).
    swap   ; Get n back into place.
    push 2
    sub
    call 0 ; Call fib(n - 2).
    add    ; Leave the sum on the stack.
1:
    ret
Output:
$ echo 10 | wspace fibrec.ws
55

Wrapl

Generator

DEF fib() (
    VAR seq <- [0, 1]; EVERY SUSP seq:values;
    REP SUSP seq:put(seq:pop + seq[1])[-1];
);

To get the 17th number:

16 SKIP fib();

To get the list of all 17 numbers:

ALL 17 OF fib();

Iterator

Using type match signature to ensure integer argument:

TO fib(n @ Integer.T) (
    VAR seq <- [0, 1];
    EVERY 3:to(n) DO seq:put(seq:pop + seq[1]);
    RET seq[-1];
);

Wren

// iterative (quick)
var fibItr = Fn.new { |n|
    if (n < 2) return n
    var a = 0
    var b = 1
    for (i in 2..n) {
        var c = a + b
        a = b
        b = c
    }
    return b
}

// recursive (slow)
var fibRec
fibRec = Fn.new { |n|
    if (n < 2) return n
    return fibRec.call(n-1) + fibRec.call(n-2)
}

System.print("Iterative: %(fibItr.call(36))")
System.print("Recursive: %(fibRec.call(36))")
Output:
Iterative: 14930352
Recursive: 14930352

x86 Assembly

Works with: MASM
TITLE i hate visual studio 4			(Fibs.asm)
;       __         __/--------\
;      >__ \      /  |        |\
;         \  \___/ @  \      /   \__________________
;           \____       \  /                         \\\
;                \____         Coded with love by:    |||
;                      \      Alexander Alvonellos    |||
;                       |          9/29/2011         / ||
;                       |                           |  MM
;                       |      |--------------|     |
;                       |<     |              |<    |
;                       |      |              |     |
;                       |mmmmmm|              |mmmmm|
;; Epic Win. 

INCLUDE Irvine32.inc
                                                                              
.data
	BEERCOUNT = 48;
	Fibs dd 0, 1, BEERCOUNT DUP(0);

.code
main PROC
; I am not responsible for this code.
; They made me write it, against my will.
	;Here be dragons
	mov esi, offset Fibs; offset array;  ;;were to start (start)
	mov ecx, BEERCOUNT; 		;;count of items (how many)
	mov ebx, 4; 		;;size (in number of bytes)
	call DumpMem;
	
	mov ecx, BEERCOUNT; 	;//http://www.wolframalpha.com/input/?i=F ib%5B47%5D+%3E+4294967295
	mov esi, offset Fibs
	NextPlease:;
		mov eax, [esi]; 	;//Get me the data from location at ESI
		add eax, [esi+4];	;//add into the eax the data at esi + another double (next mem loc)
		mov [esi+8], eax;	;//Move that data into the memory location after the second number
		add esi, 4;			;//Update the pointer
	loop NextPlease;	;//Thank you sir, may I have another?
	
	
	;Here be dragons
	mov esi, offset Fibs; offset array;  ;;were to start (start)
	mov ecx, BEERCOUNT; 		;;count of items (how many)
	mov ebx, 4; 		;;size (in number of bytes)
	call DumpMem;

	exit		; exit to operating system
main ENDP

END main

xEec

This will display the first 93 numbers of the sequence.

h#1 h#1 h#1 o# 
h#10 o$ p 
>f 
  o# h#10 o$ p 
  ma h? jnext p
  t
jnf

XLISP

Analytic

Uses Binet's method, based on the golden ratio, which almost feels like cheating—but the task specification doesn't require any particular algorithm, and this one is straightforward and fast.

(DEFUN FIBONACCI (N)
    (FLOOR (+ (/ (EXPT (/ (+ (SQRT 5) 1) 2) N) (SQRT 5)) 0.5)))

To test it, we'll define a RANGE function and ask for the first 50 numbers in the sequence:

(DEFUN RANGE (X Y)
    (IF (<= X Y)
        (CONS X (RANGE (+ X 1) Y))))

(PRINT (MAPCAR FIBONACCI (RANGE 1 50)))
Output:
(1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 12586269025)

Tail recursive

Alternatively, this approach is reasonably efficient:

(defun fibonacci (x)
    (defun fib (a b n)
        (if (= n 2)
            b
            (fib b (+ a b) (- n 1)) ) )
    (if (< x 2)
        x
        (fib 1 1 x) ) )

XPL0

func Fib1(N);   \Return Nth Fibonacci number using iteration
int N;
int Fn, F0, F1;
[F0:= 0;  F1:= 1;  Fn:= N;
while N > 1 do
        [Fn:= F0 + F1;
        F0:= F1;
        F1:= Fn;
        N:= N-1;
        ];
return Fn;
];

func Fib2(N);   \Return Nth Fibonacci number using recursion
int N;
return if N < 2 then N else Fib2(N-1) + Fib2(N-2);

int N;
[for N:= 0 to 20 do [IntOut(0, Fib1(N));  ChOut(0, ^ )];
 CrLf(0);
 for N:= 0 to 20 do [IntOut(0, Fib2(N));  ChOut(0, ^ )];
 CrLf(0);
]
Output:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 

XQuery

declare function local:fib($n as xs:integer) as xs:integer {
  if($n < 2)
  then $n
  else local:fib($n - 1) + local:fib($n - 2)
};

Z80 Assembly

; 8 bit version
; IN : a = n  (n <= 13, otherwise overflows)
; OUT: a = FIB(n)

fib8:	cp 2
	ret c	; if n < 2 then done

	ld b,a
	dec b	; b = n - 1
	ld c,0	; F0
	ld a,1	; F1

f8_l:	ld d,a
	add a,c
	ld c,d
	djnz f8_l

	ret

8 bits only? That's so 80's!

Let's go 32 bits...

; 32 bit version
; IN : a = n  (n <= 47, otherwise overflows)
; OUT: hlh'l' = FIB(n)

fib32:	ld l,a	; lower bytes in the alt set
	ld h,0
	exx	; now in regular set
	ld hl,0
	cp 2
	ret c	; if n < 2 then done

	dec a	; loopcount = n - 1
	ld bc,0
	exx	; now in alt set
	ld bc,0
	ld hl,1

f32_l:	ld d,h
	ld e,l
	add hl,bc
	ld b,d
	ld c,e
	exx	; now in reg set
	ld d,h
	ld e,l
	adc hl,bc
	ld b,d
	ld c,e
	exx	; now in alt set
	dec a
	jr nz,f32_l

	exx	; now in reg set
	ret

YAMLScript

!yamlscript/v0

defn main(n=10):
  loop [a 0, b 1, i 1]:
    say: a
    if (i < n):
      recur: b, (a + b), (i + 1)

zkl

A slight tweak to the task; creates a function that continuously generates fib numbers

var fibShift=fcn(ab){ab.append(ab.sum()).pop(0)}.fp(L(0,1));
zkl: do(15){ fibShift().print(",") }
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,

zkl: do(5){ fibShift().print(",") }
610,987,1597,2584,4181,
  1. R. L. Graham and N. J. A. Sloane, Anti-Hadamard matrices, Linear Algebra Appl. 62 (1984), 113–137.