Fibonacci sequence: Difference between revisions

m
FutureBasic entry moved out of the Basic group
m (FutureBasic entry moved out of the Basic group)
(112 intermediate revisions by 53 users not shown)
Line 38:
 
=={{header|0815}}==
<langsyntaxhighlight lang="0815">
%<:0D:>~$<:01:~%>=<:a94fad42221f2702:>~>
}:_s:{x{={~$x+%{=>~>x~-x<:0D:~>~>~^:_s:?
</syntaxhighlight>
</lang>
 
=={{header|11l}}==
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F fib_iter(n)
I n < 2
R n
Line 57:
L(i) 1..20
print(fib_iter(i), end' ‘ ’)
print()</langsyntaxhighlight>
 
{{out}}
Line 67:
For maximum compatibility, programs use only the basic instruction set.
===using fullword integers===
<langsyntaxhighlight lang="360asm">* Fibonacci sequence 05/11/2014
* integer (31 bits) = 10 decimals -> max fibo(46)
FIBONACC CSECT
Line 117:
WTOBUF DC CL80'fibo(12)=1234567890'
REGEQU
END FIBONACC</langsyntaxhighlight>
{{out}}
<pre>
Line 129:
</pre>
===using packed decimals===
<langsyntaxhighlight lang="360asm">* Fibonacci sequence 31/07/2018
* packed dec (PL8) = 15 decimals => max fibo(73)
FIBOWTOP CSECT
Line 176:
WTOBUF DC CL80'fibo(12)=123456789012345 '
REGEQU
END FIBOWTOP</langsyntaxhighlight>
{{out}}
<pre>
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.
<langsyntaxhighlight lang="6502asm"> LDA #0
STA $F0 ; LOWER NUMBER
LDA #1
Line 207:
CPX #$0A ; STOP AT FIB(10)
BMI LOOP
RTS ; RETURN FROM SUBROUTINE</langsyntaxhighlight>
 
=={{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.)
<langsyntaxhighlight lang="68000devpac">fib:
MOVEM.L D4-D5,-(SP)
MOVE.L D0,D4
Line 231:
ADD.L D4,D0
MOVEM.L (SP)+,D4-D5
RTS</langsyntaxhighlight>
 
=={{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>.
<langsyntaxhighlight lang="8080asm">FIBNCI: MOV C, A ; C will store the counter
DCR C ; decrement, because we know f(1) already
MVI A, 1
Line 244:
DCR C
JNZ LOOP ; jump if not zero
RET ; return from subroutine</langsyntaxhighlight>
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}}==
Line 251 ⟶ 359:
 
The max input is 24 before you start having 16-bit overflow.
<langsyntaxhighlight 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.
Line 280 ⟶ 388:
pop BX
pop BP
ret</langsyntaxhighlight>
 
===Using A Lookup Table===
Line 291 ⟶ 399:
 
For the purpose of this example, assume that both this code and the table are in the <code>.CODE</code> segment.
<langsyntaxhighlight 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
Line 321 ⟶ 429:
dword 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269
dword 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986
dword 102334155 </langsyntaxhighlight>
 
=={{header|8th}}==
An iterative solution:
<langsyntaxhighlight lang="forth">
: fibon \ n -- fib(n)
>r 0 1
Line 334 ⟶ 442:
dup 1 n:= if 1 ;; then
fibon nip ;
</syntaxhighlight>
</lang>
 
=={{header|ABAP}}==
===Iterative===
<langsyntaxhighlight ABAPlang="abap">FORM fibonacci_iter USING index TYPE i
CHANGING number_fib TYPE i.
DATA: lv_old type i,
Line 351 ⟶ 459:
lv_cur = number_fib.
enddo.
ENDFORM.</langsyntaxhighlight>
 
===Impure Functional===
{{works with|ABAP|7.4 SP08 Or above only}}
<langsyntaxhighlight ABAPlang="abap">cl_demo_output=>display( REDUCE #( INIT fibnm = VALUE stringtab( ( |0| ) ( |1| ) )
n TYPE string
x = `0`
Line 363 ⟶ 471:
fibnm = VALUE #( BASE fibnm ( n ) )
x = y
y = n ) ).</langsyntaxhighlight>
 
=={{header|ACL2}}==
Fast, tail recursive solution:
<langsyntaxhighlight Lisplang="lisp">(defun fast-fib-r (n a b)
(if (or (zp n) (zp (1- n)))
b
Line 383 ⟶ 491:
 
(defun first-fibs (n)
(first-fibs-r n 0))</langsyntaxhighlight>
 
{{out}}
Line 393 ⟶ 501:
=={{header|Action!}}==
Action! language does not support recursion. Therefore an iterative approach has been proposed.
<langsyntaxhighlight Actionlang="action!">INT FUNC Fibonacci(INT n)
INT curr,prev,tmp
 
Line 440 ⟶ 548:
FI
OD
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Fibonacci_sequence.png Screenshot from Atari 8-bit computer]
Line 470 ⟶ 578:
 
=={{header|ActionScript}}==
<langsyntaxhighlight lang="actionscript">public function fib(n:uint):uint
{
if (n < 2)
Line 476 ⟶ 584:
return fib(n - 1) + fib(n - 2);
}</langsyntaxhighlight>
 
=={{header|Ada}}==
 
===Recursive===
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Ada.Command_Line;
 
procedure Fib is
Line 499 ⟶ 607:
Ada.Text_IO.Put("Fibonacci(" & Integer'Image(X) & " ) = ");
Ada.Text_IO.Put_Line(Integer'Image(Fib(X)));
end Fib;</langsyntaxhighlight>
 
===Iterative, build-in integers===
<langsyntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
 
procedure Test_Fibonacci is
Line 521 ⟶ 629:
Put_Line (Positive'Image (Fibonacci (N)));
end loop;
end Test_Fibonacci;</langsyntaxhighlight>
{{out}}
<pre>
Line 541 ⟶ 649:
Using the big integer implementation from a cryptographic library [https://github.com/cforler/Ada-Crypto-Library/].
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Ada.Command_Line, Crypto.Types.Big_Numbers;
 
procedure Fibonacci is
Line 573 ⟶ 681:
Ada.Text_IO.Put("Fibonacci(" & Integer'Image(X) & " ) = ");
Ada.Text_IO.Put_Line(LN.Utils.To_String(Fib(X)));
end Fibonacci;</langsyntaxhighlight>
 
{{out}}
Line 581 ⟶ 689:
===Fast method using fast matrix exponentiation===
 
<syntaxhighlight lang="ada">
<lang Ada>
with ada.text_io;
use ada.text_io;
Line 630 ⟶ 738:
-- calculate instantly F_n with n=10^15 (modulus 2^64 )
put_line (Big_Int_Fibo (10**15)'img);
end fast_fibo; </langsyntaxhighlight>
 
=={{header|AdvPL}}==
===Recursive===
<syntaxhighlight lang="advpl">
<lang AdvPL>
#include "totvs.ch"
User Function fibb(a,b,n)
return(if(--n>0,fibb(b,a+b,n),a))
</syntaxhighlight>
</lang>
 
===Iterative===
<syntaxhighlight lang="advpl">
<lang AdvPL>
#include "totvs.ch"
User Function fibb(n)
Line 651 ⟶ 759:
end while
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}}==
<langsyntaxhighlight lang="aime">integer
fibs(integer n)
{
Line 679 ⟶ 801:
return w;
}
</syntaxhighlight>
</lang>
 
=={{header|ALGOL 60}}==
{{works with|A60}}
<langsyntaxhighlight lang="algol60">begin
comment Fibonacci sequence;
integer procedure fibonacci(n); value n; integer n;
Line 701 ⟶ 823:
integer i;
for i := 0 step 1 until 20 do outinteger(1,fibonacci(i))
end </langsyntaxhighlight>
{{out}}
<pre>
Line 714 ⟶ 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|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]}}
<langsyntaxhighlight lang="algol68">PROC analytic fibonacci = (LONG INT n)LONG INT:(
LONG REAL sqrt 5 = long sqrt(5);
LONG REAL p = (1 + sqrt 5) / 2;
Line 726 ⟶ 848:
print(", ")
OD;
print(new line)</langsyntaxhighlight>
{{out}}
<pre>
Line 736 ⟶ 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|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]}}
<langsyntaxhighlight lang="algol68">PROC iterative fibonacci = (INT n)INT:
CASE n+1 IN
0, 1, 1, 2, 3, 5
Line 752 ⟶ 874:
print(", ")
OD;
print(new line)</langsyntaxhighlight>
{{out}}
<pre>
Line 761 ⟶ 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|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]}}
<langsyntaxhighlight lang="algol68">PROC recursive fibonacci = (INT n)INT:
( n < 2 | n | fib(n-1) + fib(n-2));</langsyntaxhighlight>
===Generative===
{{trans|Python|Note: This specimen retains the original [[Prime decomposition#Python|Python]] coding style.}}
Line 768 ⟶ 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|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]}}
<langsyntaxhighlight lang="algol68">MODE YIELDINT = PROC(INT)VOID;
 
PROC gen fibonacci = (INT n, YIELDINT yield)VOID: (
Line 785 ⟶ 907:
# OD # ));
print(new line)
)</langsyntaxhighlight>
{{out}}
<pre>
Line 797 ⟶ 919:
 
This uses a pre-generated list, requiring much less run-time processor usage, but assumes that INT is only 31 bits wide.
<langsyntaxhighlight lang="algol68">[]INT const fibonacci = []INT( -1836311903, 1134903170,
-701408733, 433494437, -267914296, 165580141, -102334155,
63245986, -39088169, 24157817, -14930352, 9227465, -5702887,
Line 826 ⟶ 948:
print(", ")
OD;
print(new line)</langsyntaxhighlight>
{{out}}
<pre>
Line 833 ⟶ 955:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% return the nth Fibonacci number %
integer procedure Fibonacci( integer value n ) ;
Line 851 ⟶ 973:
for i := 0 until 10 do writeon( i_w := 3, s_w := 0, Fibonacci( i ) )
 
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 860 ⟶ 982:
Note that the 21st Fibonacci number (= 10946) is the largest that can be calculated without overflowing ALGOL-M's integer data type.
====Iterative====
<langsyntaxhighlight lang="algol">INTEGER FUNCTION FIBONACCI( X ); INTEGER X;
BEGIN
INTEGER M, N, A, I;
Line 872 ⟶ 994:
END;
FIBONACCI := N;
END;</langsyntaxhighlight>
 
====Naively recursive====
<langsyntaxhighlight lang="algol">INTEGER FUNCTION FIBONACCI( X ); INTEGER X;
BEGIN
IF X < 3 THEN
Line 881 ⟶ 1,003:
ELSE
FIBONACCI := FIBONACCI( X - 2 ) + FIBONACCI( X - 1 );
END;</langsyntaxhighlight>
 
=={{header|Alore}}==
 
<langsyntaxhighlight Alorelang="alore">def fib(n as Int) as Int
if n < 2
return 1
end
return fib(n-1) + fib(n-2)
end</langsyntaxhighlight>
 
=={{header|Amazing Hopper}}==
Analitic, Recursive and Iterative mode.
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <hbasic.h>
 
Line 937 ⟶ 1,059:
Next
Return(B)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 947 ⟶ 1,069:
 
=={{header|AntLang}}==
<langsyntaxhighlight AntLanglang="antlang">/Sequence
fib:{<0;1> {x,<x[-1]+x[-2]>}/ range[x]}
/nth
fibn:{fib[x][x]}</langsyntaxhighlight>
 
=={{header|Apex}}==
 
<syntaxhighlight lang="apex">
<lang Apex>
/*
author: snugsfbay
Line 998 ⟶ 1,120:
}
</syntaxhighlight>
</lang>
 
=={{header|APL}}==
Line 1,005 ⟶ 1,127:
 
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">
<lang APL>
fib←{⍵≤1:⍵ ⋄ (∇ ⍵-1)+∇ ⍵-2}
</syntaxhighlight>
</lang>
 
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.
Line 1,020 ⟶ 1,142:
:<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:
<syntaxhighlight lang="apl">
<lang APL>
↑+.×/N/⊂2 2⍴1 1 1 0
</syntaxhighlight>
</lang>
Plugging in 4 for N gives the following result:
:<math>\begin{pmatrix} 5 & 3 \\ 3 & 2 \end{pmatrix}</math>
Line 1,029 ⟶ 1,151:
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:
<syntaxhighlight lang="apl">
<lang APL>
↑0 1↓↑+.×/N/⊂2 2⍴1 1 1 0
</syntaxhighlight>
</lang>
 
====Analytic====
Line 1,037 ⟶ 1,159:
{{works with|GNU APL}}
An alternative approach, using Binet's formula (which was apparently known long before Binet):
<langsyntaxhighlight lang="apl">⌊.5+(((1+PHI)÷2)*⍳N)÷PHI←5*.5</langsyntaxhighlight>
 
=={{header|AppleScript}}==
Line 1,044 ⟶ 1,166:
===Imperative===
 
<langsyntaxhighlight 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 x as integer
Line 1,054 ⟶ 1,176:
end if
end repeat
return item x of fibs</langsyntaxhighlight>
 
 
Line 1,062 ⟶ 1,184:
The simple recursive version is famously slow:
 
<langsyntaxhighlight AppleScriptlang="applescript">on fib(n)
if n < 1 then
0
Line 1,070 ⟶ 1,192:
fib(n - 2) + fib(n - 1)
end if
end fib</langsyntaxhighlight>
 
but we can combine '''enumFromTo(m, n)''' with the accumulator of a higher-order '''fold/reduce''' function to memoize the series:
Line 1,076 ⟶ 1,198:
{{Trans|JavaScript}} (ES6 memoized fold example)
{{Trans|Haskell}} (Memoized fold example)
<langsyntaxhighlight AppleScriptlang="applescript">-------------------- FIBONACCI SEQUENCE --------------------
 
-- fib :: Int -> Int
Line 1,137 ⟶ 1,259:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<pre>2178309</pre>
Line 1,157 ⟶ 1,279:
=={{header|ARM Assembly}}==
Expects to be called with <math>n</math> in R0, and will return <math>f(n)</math> in the same register.
<langsyntaxhighlight lang="armasm">fibonacci:
push {r1-r3}
mov r1, #0
Line 1,172 ⟶ 1,294:
mov r0, r2
pop {r1-r3}
mov pc, lr</langsyntaxhighlight>
 
=={{header|ArnoldC}}==
 
<langsyntaxhighlight ArnoldClang="arnoldc">IT'S SHOWTIME
 
HEY CHRISTMAS TREE f1
Line 1,206 ⟶ 1,328:
CHILL
 
YOU HAVE BEEN TERMINATED</langsyntaxhighlight>
 
=={{header|Arturo}}==
Line 1,212 ⟶ 1,334:
===Recursive===
 
<langsyntaxhighlight lang="arturo">fib: $[x][
if? x<2 [1]
else [(fib x-1) + (fib x-2)]
Line 1,219 ⟶ 1,341:
loop 1..25 [x][
print ["Fibonacci of" x "=" fib x]
]</langsyntaxhighlight>
 
=={{header|AsciiDots}}==
 
<syntaxhighlight lang="asciidots">
<lang AsciiDots>
 
/--#$--\
Line 1,235 ⟶ 1,357:
. .
 
</syntaxhighlight>
</lang>
 
=={{header|ATS}}==
===Recursive===
<syntaxhighlight lang="ats">
<lang ATS>
fun fib_rec(n: int): int =
if n >= 2 then fib_rec(n-1) + fib_rec(n-2) else n
</syntaxhighlight>
</lang>
 
===Iterative===
<syntaxhighlight lang="ats">
<lang ATS>
(*
** This one is also referred to as being tail-recursive
Line 1,255 ⟶ 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)
else 0
</syntaxhighlight>
</lang>
 
===Iterative and Verified===
<syntaxhighlight lang="ats">
<lang ATS>
(*
** This implementation is verified!
Line 1,286 ⟶ 1,408:
loop {0} (FIB0 (), FIB1 () | n, 0, 1)
end // end of [fibats]
</syntaxhighlight>
</lang>
 
===Matrix-based===
<syntaxhighlight lang="ats">
<lang ATS>
(* ****** ****** *)
//
Line 1,369 ⟶ 1,491:
//
} (* end of [main0] *)
</syntaxhighlight>
</lang>
 
=={{header|AutoHotkey}}==
Line 1,376 ⟶ 1,498:
===Iterative===
{{trans|C}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">Loop, 5
MsgBox % fib(A_Index)
Return
Line 1,393 ⟶ 1,515:
}
Return this
}</langsyntaxhighlight>
 
===Recursive and iterative===
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
without a global or static array. The iterative version
Line 1,413 ⟶ 1,535:
c := b, b += a, a := c
Return n=0 ? 0 : n>0 || n&1 ? b : -b
}</langsyntaxhighlight>
 
=={{header|AutoIt}}==
===Iterative===
<langsyntaxhighlight AutoItlang="autoit">#AutoIt Version: 3.2.10.0
$n0 = 0
$n1 = 1
Line 1,444 ⟶ 1,566:
Return $febo
EndFunc
</syntaxhighlight>
</lang>
===Recursive===
<langsyntaxhighlight AutoItlang="autoit">#AutoIt Version: 3.2.10.0
$n0 = 0
$n1 = 1
Line 1,465 ⟶ 1,587:
EndIf
EndFunc
</syntaxhighlight>
</lang>
 
=={{header|AWK}}==
As in many examples, this one-liner contains the function as well as testing with input from stdin, output to stdout.
<langsyntaxhighlight lang="awk">$ awk 'func fib(n){return(n<2?n:fib(n-1)+fib(n-2))}{print "fib("$1")="fib($1)}'
10
fib(10)=55</langsyntaxhighlight>
 
=={{header|Axe}}==
Line 1,478 ⟶ 1,600:
 
Iterative solution:
<langsyntaxhighlight lang="axe">Lbl FIB
r₁→N
0→I
Line 1,488 ⟶ 1,610:
End
J
Return</langsyntaxhighlight>
 
=={{header|Babel}}==
In Babel, we can define fib using a stack-based approach that is not recursive:
 
<langsyntaxhighlight lang="babel">fib { <- 0 1 { dup <- + -> swap } -> times zap } <</langsyntaxhighlight>
 
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:
Line 1,505 ⟶ 1,627:
And so on. To test fib:
 
<langsyntaxhighlight lang="babel">{19 iter - fib !} 20 times collect ! lsnum !</langsyntaxhighlight>
 
{{out}}
Line 1,512 ⟶ 1,634:
=={{header|bash}}==
===Iterative===
<langsyntaxhighlight lang="bash">
$ fib=1;j=1;while((fib<100));do echo $fib;((k=fib+j,fib=j,j=k));done
</syntaxhighlight>
</lang>
<pre>
1
Line 1,530 ⟶ 1,652:
 
===Recursive===
<langsyntaxhighlight lang="bash">fib()
{
if [ $1 -le 0 ]
Line 1,546 ⟶ 1,668:
fi
}
</syntaxhighlight>
</lang>
 
=={{header|BASIC}}==
Line 1,556 ⟶ 1,678:
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">
<lang BASIC256>
# Basic-256 ver 1.1.4
# iterative Fibonacci sequence
Line 1,581 ⟶ 1,703:
print " "
print n + chr(9) + c
</syntaxhighlight>
</lang>
 
==={{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}}
<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|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}}===
<langsyntaxhighlight 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
Line 1,599 ⟶ 1,810:
230 : PRINT ","; STR$(A);
240 NEXT I
250 PRINT</langsyntaxhighlight>
 
{{Out}}
Line 1,609 ⟶ 1,820:
 
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>.
<langsyntaxhighlight lang="basic"> 10 INPUT N
20 A=0
30 B=1
Line 1,621 ⟶ 2,098:
80 NEXT I
90 PRINT B
100 END</langsyntaxhighlight>
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Fibonac.bas"
110 FOR I=0 TO 20
120 PRINT "F";I,FIB(I)
Line 1,635 ⟶ 2,112:
190 NEXT
200 LET FIB=A
210 END DEF</langsyntaxhighlight>
 
==={{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}}===
Line 1,641 ⟶ 2,538:
{{works with|FreeBASIC}}
====Iterative====
<langsyntaxhighlight lang="qbasic">FUNCTION itFib (n)
n1 = 0
n2 = 1
Line 1,654 ⟶ 2,551:
itFib = n1
END IF
END FUNCTION</langsyntaxhighlight>
 
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):
 
<langsyntaxhighlight lang="qbasic">DECLARE FUNCTION fibonacci& (n AS INTEGER)
 
REDIM SHARED fibNum(1) AS LONG
Line 1,695 ⟶ 2,592:
ERROR 6 'overflow
END SELECT
END FUNCTION</langsyntaxhighlight>
 
{{out}} (unhandled error in final input prevents output):
Line 1,706 ⟶ 2,603:
====Recursive====
This example can't handle n < 0.
<syntaxhighlight lang="qbasic">FUNCTION recFib (n)
 
<lang qbasic>FUNCTION recFib (n)
IF (n < 2) THEN
recFib = n
Line 1,713 ⟶ 2,609:
recFib = recFib(n - 1) + recFib(n - 2)
END IF
END FUNCTION</langsyntaxhighlight>
 
====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.)
 
<langsyntaxhighlight lang="qbasic">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
Line 1,739 ⟶ 2,634:
NEXT
PRINT
'*****sample inputs*****</langsyntaxhighlight>
 
===={{header|QB64Quite BASIC}}====
<syntaxhighlight lang="qbasic">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</syntaxhighlight>
 
==={{header|Run BASIC}}===
Fibonacci from Russia
<syntaxhighlight 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</syntaxhighlight>
 
==={{header|S-BASIC}}===
<lang qbasic>DIM F(80) AS DOUBLE 'FibRus.bas DANILIN
Note that the 23rd Fibonacci number (=28657) is the largest that can be generated without overflowing S-BASIC's integer data type.
F(1) = 0: F(2) = 1
<syntaxhighlight lang="basic">
'OPEN "FibRus.txt" FOR OUTPUT AS #1
rem - iterative function to calculate nth fibonacci number
FOR i = 3 TO 80
function fibonacci(n = integer) = integer
F(i) = F(i-1)+F(i-2)
var f, i, p1, p2 = integer
NEXT i
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
FOR i = 1 TO 80
var i = integer
f$ = STR$(F(i)): LF = 22 - LEN(f$)
for i = 0 n$ =to ""10
print fibonacci(i);
FOR j = 1 TO LF: n$ = " " + n$: NEXT
next i
f$ = n$ + f$
 
PRINT i, f$: ' PRINT #1, i, f$
end
NEXT i</lang>
</syntaxhighlight>
{{out}}
<pre>1 0 1 1 2 3 5 8 13 21 34 055
</pre>
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|Sinclair ZX81 BASIC}}===
====Analytic====
<langsyntaxhighlight lang="basic"> 10 INPUT N
20 PRINT INT (0.5+(((SQR 5+1)/2)**N)/SQR 5)</langsyntaxhighlight>
 
====Iterative====
<langsyntaxhighlight lang="basic"> 10 INPUT N
20 LET A=0
30 LET B=1
Line 1,806 ⟶ 2,714:
70 LET A=C
80 NEXT I
90 PRINT B</langsyntaxhighlight>
 
====Tail recursive====
<langsyntaxhighlight lang="basic"> 10 INPUT N
20 LET A=0
30 LET B=1
Line 1,821 ⟶ 2,729:
110 LET N=N-1
120 GOSUB 70
130 RETURN</langsyntaxhighlight>
 
==={{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}}==
Recursive version
<langsyntaxhighlight lang="dos">::fibo.cmd
@echo off
if "%1" equ "" goto :eof
Line 1,845 ⟶ 3,228:
set r2=%errorlevel%
set /a r0 = r1 + r2
exit /b !r0!</langsyntaxhighlight>
 
{{out}}
Line 1,866 ⟶ 3,249:
 
<!--- works with C syntax highlighting --->
<syntaxhighlight lang="c">
<lang c>
// Fibonacci sequence, recursive version
fun fibb
Line 1,910 ⟶ 3,293:
 
// 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}}==
=== iterative ===
<langsyntaxhighlight lang="bc">#! /usr/bin/bc -q
 
define fib(x) {
Line 1,954 ⟶ 3,311:
}
fib(1000)
quit</langsyntaxhighlight>
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
let fib(n) = n<=1 -> n, valof
Line 1,971 ⟶ 3,328:
let start() be
for i=0 to 10 do
writef("F_%N*T= %N*N", i, fib(i))</langsyntaxhighlight>
{{out}}
<pre>F_0 = 0
Line 1,987 ⟶ 3,344:
=={{header|beeswax}}==
 
<langsyntaxhighlight lang="beeswax"> #>'#{;
_`Enter n: `TN`Fib(`{`)=`X~P~K#{;
#>~P~L#MM@>+@'q@{;
b~@M<</langsyntaxhighlight>
 
Example output:
Line 1,996 ⟶ 3,353:
Notice the UInt64 wrap-around at <code>Fib(94)</code>!
 
<langsyntaxhighlight lang="julia">julia> beeswax("n-th Fibonacci number.bswx")
Enter n: i0
 
Line 2,024 ⟶ 3,381:
Fib(94)=1293530146158671551
Program finished!</langsyntaxhighlight>
 
=={{header|Befunge}}==
<langsyntaxhighlight lang="befunge">00:.1:.>:"@"8**++\1+:67+`#@_v
^ .:\/*8"@"\%*8"@":\ <</langsyntaxhighlight>
 
=={{header|BlitzMax}}==
<langsyntaxhighlight lang="blitzmax">local a:int = 0, b:int = 1, c:int = 1, n:int
 
n = int(input( "Enter n: "))
Line 2,048 ⟶ 3,405:
n = n - 1
wend
print c</langsyntaxhighlight>
 
=={{header|Blue}}==
<langsyntaxhighlight 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>
</lang>
 
=={{header|BQN}}==
Line 2,063 ⟶ 3,420:
=== Recursive ===
A primitive recursive can be done with predicates:
<langsyntaxhighlight lang="bqn">Fib ← {𝕩>1 ? (𝕊 𝕩-1) + 𝕊 𝕩-2; 𝕩}</langsyntaxhighlight>
Or, it can be done with the Choose(<code>◶</code>) modifier:
<langsyntaxhighlight lang="bqn">Fib2 ← {(𝕩-1) (𝕩>1)◶⟨𝕩, +○𝕊⟩ 𝕩-2}</langsyntaxhighlight>
 
=== Iterative ===
An iterative solution can be made with the Repeat(<code>⍟</code>) modifier:
<langsyntaxhighlight lang="bqn">{⊑(+`⌽)⍟𝕩 0‿1}</langsyntaxhighlight>
 
=={{header|Bracmat}}==
===Recursive===
<langsyntaxhighlight lang="bracmat">fib=.!arg:<2|fib$(!arg+-2)+fib$(!arg+-1)</langsyntaxhighlight>
 
fib$30
Line 2,079 ⟶ 3,436:
 
===Iterative===
<langsyntaxhighlight lang="bracmat">(fib=
last i this new
. !arg:<2
Line 2,091 ⟶ 3,448:
)
& !this
)</langsyntaxhighlight>
 
fib$777
Line 2,099 ⟶ 3,456:
{{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).
<langsyntaxhighlight lang="bf">++++++++++
>>+<<[->[->+>+<<]>[-<+>]>[-<+>]<<<]</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="bf">+++++ +++++ #0 set to n
>> + Init #2 to 1
<<
Line 2,140 ⟶ 3,497:
]
<<<< Back to #0
]</langsyntaxhighlight>
 
=={{header|Brat}}==
===Recursive===
<langsyntaxhighlight lang="brat">fibonacci = { x |
true? x < 2, x, { fibonacci(x - 1) + fibonacci(x - 2) }
}</langsyntaxhighlight>
 
===Tail Recursive===
<langsyntaxhighlight lang="brat">fib_aux = { x, next, result |
true? x == 0,
result,
Line 2,157 ⟶ 3,514:
fibonacci = { x |
fib_aux x, 1, 0
}</langsyntaxhighlight>
 
===Memoization===
<langsyntaxhighlight lang="brat">cache = hash.new
 
fibonacci = { x |
Line 2,166 ⟶ 3,523:
{ cache[x] }
{true? x < 2, x, { cache[x] = fibonacci(x - 1) + fibonacci(x - 2) }}
}</langsyntaxhighlight>
 
=={{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}}==
 
<langsyntaxhighlight lang="burlesque">
{0 1}{^^++[+[-^^-]\/}30.*\[e!vv
</syntaxhighlight>
</lang>
 
<langsyntaxhighlight lang="burlesque">
0 1{{.+}c!}{1000.<}w!
</syntaxhighlight>
</lang>
 
=={{header|C}}==
===Recursive===
<langsyntaxhighlight lang="c">long long fibb(long long a, long long b, int n) {
return (--n>0)?(fibb(b, a+b, n)):(a);
}</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight lang="c">long long int fibb(int n) {
int fnow = 0, fnext = 1, tempf;
while(--n>0){
Line 2,193 ⟶ 3,587:
}
return fnext;
}</langsyntaxhighlight>
 
===Analytic===
<langsyntaxhighlight lang="c">#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) );
}</langsyntaxhighlight>
 
===Generative===
{{trans|Python}}
{{works with|gcc|version 4.1.2 20080704 (Red Hat 4.1.2-44)}}
<langsyntaxhighlight lang="c">#include <stdio.h>
typedef enum{false=0, true=!0} bool;
typedef void iterator;
Line 2,242 ⟶ 3,636:
OD;
printf("...\n");
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,249 ⟶ 3,643:
 
===Fast method for a single large value===
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
#include <gmp.h>
Line 2,322 ⟶ 3,716:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,339 ⟶ 3,733:
 
=== Recursive ===
<langsyntaxhighlight lang="csharp">
public static ulong Fib(uint n) {
return (n < 2)? n : Fib(n - 1) + Fib(n - 2);
}
</syntaxhighlight>
</lang>
 
=== Tail-Recursive ===
<langsyntaxhighlight lang="csharp">
public static ulong Fib(uint n) {
return Fib(0, 1, n);
Line 2,354 ⟶ 3,748:
return (n < 1)? a :(n == 1)? b : Fib(b, a + b, n - 1);
}
</syntaxhighlight>
</lang>
 
=== Iterative ===
<langsyntaxhighlight lang="csharp">
public static ulong Fib(uint x) {
if (x == 0) return 0;
Line 2,371 ⟶ 3,765:
return next;
}
</syntaxhighlight>
</lang>
 
=== 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 ===
<langsyntaxhighlight lang="csharp">
public static IEnumerable<long> Fibs(uint x) {
IList<ulong> fibs = new List<ulong>();
Line 2,389 ⟶ 3,808:
return fibs;
}
</syntaxhighlight>
</lang>
 
=== Lazy-Generative ===
<langsyntaxhighlight lang="csharp">
public static IEnumerable<ulong> Fibs(uint x) {
ulong prev = -1;
Line 2,403 ⟶ 3,822:
}
}
</syntaxhighlight>
</lang>
 
=== 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>.
<langsyntaxhighlight 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)); }</langsyntaxhighlight>To get to the 93<sup>rd</sup> Fibonacci number, one must use the decimal type, rather than the double type, like this:<langsyntaxhighlight 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; }
Line 2,427 ⟶ 3,846:
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)); }</langsyntaxhighlight>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><langsyntaxhighlight 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; }
Line 2,442 ⟶ 3,861:
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); }</langsyntaxhighlight>
 
=== Matrix ===
Line 2,450 ⟶ 3,869:
Needs <code>System.Windows.Media.Matrix</code> or similar Matrix class.
Calculates in <math>O(n)</math>.
<langsyntaxhighlight lang="csharp">
public static ulong Fib(uint n) {
var M = new Matrix(1,0,0,1);
Line 2,457 ⟶ 3,876:
return (ulong)M[0][0];
}
</syntaxhighlight>
</lang>
Needs <code>System.Windows.Media.Matrix</code> or similar Matrix class.
Calculates in <math>O(\log{n})</math>.
<langsyntaxhighlight lang="csharp">
private static Matrix M;
private static readonly Matrix N = new Matrix(1,1,1,0);
Line 2,477 ⟶ 3,896:
if (n % 2 == 0) M *= N;
}
</syntaxhighlight>
</lang>
 
=== Array (Table) Lookup ===
<langsyntaxhighlight lang="csharp">
private static int[] fibs = new int[]{ -1836311903, 1134903170,
-701408733, 433494437, -267914296, 165580141, -102334155,
Line 2,498 ⟶ 3,917:
return fibs[n+46];
}
</syntaxhighlight>
</lang>
===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).
 
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
Line 2,546 ⟶ 3,965:
Console.Write("partial: {0}...{1}", v / BI.Pow(10, vlen - digs), v % BI.Pow(10, digs));
}
}</langsyntaxhighlight>
{{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++}}==
Using unsigned int, this version only works up to 48 before fib overflows.
<langsyntaxhighlight lang="cpp">#include <iostream>
 
int main()
Line 2,569 ⟶ 4,027:
 
return 0;
}</langsyntaxhighlight>
 
 
Line 2,575 ⟶ 4,033:
This version does not have an upper bound.
 
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <gmpxx.h>
 
Line 2,595 ⟶ 4,053:
}
return 0;
}</langsyntaxhighlight>
 
Version using transform:
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <vector>
#include <functional>
Line 2,610 ⟶ 4,068:
// "v" now contains the Fibonacci sequence from 0 up
return v[n];
}</langsyntaxhighlight>
 
Far-fetched version using adjacent_difference:
<langsyntaxhighlight lang="cpp">#include <numeric>
#include <vector>
#include <functional>
Line 2,625 ⟶ 4,083:
return v[n-1];
}
</syntaxhighlight>
</lang>
 
Version which computes at compile time with metaprogramming:
<langsyntaxhighlight lang="cpp">#include <iostream>
 
template <int n> struct fibo
Line 2,651 ⟶ 4,109:
std::cout<<fibo<46>::value<<std::endl;
return 0;
}</langsyntaxhighlight>
 
The following version is based on fast exponentiation:
<langsyntaxhighlight lang="cpp">#include <iostream>
 
inline void fibmul(int* f, int* g)
Line 2,688 ⟶ 4,146:
std::cout << fibonacci(i) << " ";
std::cout << std::endl;
}</langsyntaxhighlight>
{{out}}
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. [[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.
<langsyntaxhighlight lang="cpp">
// Use Zeckendorf numbers to display Fibonacci sequence.
// Nigel Galloway October 23rd., 2012
Line 2,709 ⟶ 4,167:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,717 ⟶ 4,175:
===Using Standard Template Library===
Possibly less "Far-fetched version".
<langsyntaxhighlight lang="cpp">
// Use Standard Template Library to display Fibonacci sequence.
// Nigel Galloway March 30th., 2013
Line 2,729 ⟶ 4,187:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946
 
=={{header|Cat}}==
<langsyntaxhighlight lang="cat">define fib {
dup 1 <=
[]
[dup 1 - fib swap 2 - fib +]
if
}</langsyntaxhighlight>
 
=={{header|Chapel}}==
<langsyntaxhighlight lang="chapel">iter fib() {
var a = 0, b = 1;
 
Line 2,749 ⟶ 4,207:
(a, b) = (b, b + a);
}
}</langsyntaxhighlight>
 
=={{header|Chef}}==
<langsyntaxhighlight lang="chef">Stir-Fried Fibonacci Sequence.
 
An unobfuscated iterative implementation.
Line 2,782 ⟶ 4,240:
Pour contents of the 4th mixing bowl into baking dish.
 
Serves 1.</langsyntaxhighlight>
 
=={{header|Chez Scheme}}==
<syntaxhighlight lang="scheme">
(define fib (lambda (n) (cond ((> n 1) (+ (fib (- n 1)) (fib (- n 2))))
((= n 1) 1)
((= n 0) 0))))
</syntaxhighlight>
 
=={{header|Clio}}==
Line 2,788 ⟶ 4,253:
Clio is pure and functions are lazy and memoized by default
 
<langsyntaxhighlight lang="clio">fn fib n:
if n < 2: n
else: (n - 1 -> fib) + (n - 2 -> fib)
 
[0:100] -> * fib -> * print</langsyntaxhighlight>
 
=={{header|Clojure}}==
Line 2,798 ⟶ 4,263:
===Lazy Sequence===
This is implemented idiomatically as an infinitely long, lazy sequence of all Fibonacci numbers:
<langsyntaxhighlight Clojurelang="clojure">(defn fibs []
(map first (iterate (fn [[a b]] [b (+ a b)]) [0 1])))</langsyntaxhighlight>
Thus to get the nth one:
<syntaxhighlight lang Clojure="clojure">(nth (fibs) 5)</langsyntaxhighlight>
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.
<langsyntaxhighlight Clojurelang="clojure">(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</langsyntaxhighlight>
 
A more elegant solution is inspired by the Haskell implementation of an infinite list of Fibonacci numbers:
<langsyntaxhighlight Clojurelang="clojure">(def fib (lazy-cat [0 1] (map + fib (rest fib))))</langsyntaxhighlight>
Then, to see the first ten,
<langsyntaxhighlight Clojurelang="clojure">user> (take 10 fib)
(0 1 1 2 3 5 8 13 21 34)</langsyntaxhighlight>
 
===Iterative===
 
Here's a simple interative process (using a recursive function) that carries state along with it (as args) until it reaches a solution:
<langsyntaxhighlight Clojurelang="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.)
;; j is the nth fib number (ex. when n = 5, j = 5)
Line 2,838 ⟶ 4,303:
(if (< max 2)
max
(fib-iter max 1 0N 1N)))</langsyntaxhighlight>
"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.
 
Line 2,844 ⟶ 4,309:
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
<langsyntaxhighlight lang="clojure">
(defn fib [n]
(letfn [(fib* [n]
Line 2,856 ⟶ 4,321:
[d (+' c d)]))))]
(first (fib* n))))
</syntaxhighlight>
</lang>
 
===Recursive===
Line 2,862 ⟶ 4,327:
A naive slow recursive solution:
 
<langsyntaxhighlight Clojurelang="clojure">(defn fib [n]
(case n
0 0
1 1
(+ (fib (- n 1))
(fib (- n 2)))))</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight Clojurelang="clojure">(def fib
(memoize
(fn [n]
Line 2,878 ⟶ 4,343:
1 1
(+ (fib (- n 1))
(fib (- n 2)))))))</langsyntaxhighlight>
 
=== Using core.async ===
<langsyntaxhighlight Clojurelang="clojure">(ns fib.core)
(require '[clojure.core.async
:refer [<! >! >!! <!! timeout chan alt! go]])
Line 2,897 ⟶ 4,362:
(for [i (range 10)]
(println (<!! c))))))
</syntaxhighlight>
</lang>
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">% Generate Fibonacci numbers
fib = iter () yields (int)
a: int := 0
Line 2,940 ⟶ 4,405:
|| int$unparse(nth[int](fib, n)))
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>F(0) = 0
Line 2,964 ⟶ 4,429:
Iteration uses a while() loop. Memoization uses global properties.
 
<langsyntaxhighlight lang="cmake">set_property(GLOBAL PROPERTY fibonacci_0 0)
set_property(GLOBAL PROPERTY fibonacci_1 1)
set_property(GLOBAL PROPERTY fibonacci_next 2)
Line 2,991 ⟶ 4,456:
get_property(answer GLOBAL PROPERTY fibonacci_${n})
set(${var} ${answer} PARENT_SCOPE)
endfunction(fibonacci)</langsyntaxhighlight>
 
<langsyntaxhighlight lang="cmake"># Test program: print 0th to 9th and 25th to 30th Fibonacci numbers.
set(s "")
foreach(i RANGE 0 9)
Line 3,004 ⟶ 4,469:
set(s "${s} ${f}")
endforeach(i)
message(${s})</langsyntaxhighlight>
 
<pre> 0 1 1 2 3 5 8 13 21 34 ... 75025 121393 196418 317811 514229 832040</pre>
Line 3,010 ⟶ 4,475:
=={{header|COBOL}}==
===Iterative===
<langsyntaxhighlight lang="cobol">Program-ID. Fibonacci-Sequence.
Data Division.
Working-Storage Section.
Line 3,049 ⟶ 4,514:
Move INTERM-RESULT to FORMATTED-RESULT.
Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT.
Display FORMATTED-RESULT.</langsyntaxhighlight>
 
===Recursive===
{{works with|GNU Cobol|2.0}}
<langsyntaxhighlight lang="cobol"> >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. fibonacci-main.
Line 3,097 ⟶ 4,562:
END-EVALUATE
.
END PROGRAM fibonacci.</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
===Analytic===
<langsyntaxhighlight lang="coffeescript">fib_ana = (n) ->
sqrt = Math.sqrt
phi = ((1 + sqrt(5))/2)
Math.round((Math.pow(phi, n)/sqrt(5)))</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight lang="coffeescript">fib_iter = (n) ->
return n if n < 2
[prev, curr] = [0, 1]
[prev, curr] = [curr, curr + prev] for i in [1..n]
curr</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="coffeescript">fib_rec = (n) ->
if n < 2 then n else fib_rec(n-1) + fib_rec(n-2)</langsyntaxhighlight>
 
=={{header|Comefrom0x10}}==
Line 3,122 ⟶ 4,587:
 
===Iterative===
<langsyntaxhighlight lang="cf0x10">stop = 6
a = 1
i = 1 # start
Line 3,136 ⟶ 4,601:
b = next_b
 
comefrom fib if i > stop</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
Note that Common Lisp uses bignums, so this will never overflow.
===Iterative===
<langsyntaxhighlight lang="lisp">(defun fibonacci-iterative (n &aux (f0 0) (f1 1))
(case n
(0 f0)
Line 3,148 ⟶ 4,613:
for a = f0 then b and b = f1 then result
for result = (+ a b)
finally (return result)))))</langsyntaxhighlight>
 
Simpler one:
<langsyntaxhighlight lang="lisp">(defun fibonacci (n)
(let ((a 0) (b 1) (c n))
(loop for i from 2 to n do
Line 3,157 ⟶ 4,622:
a b
b c))
c))</langsyntaxhighlight>
 
Not a function, just printing out the entire (for some definition of "entire") sequence with a <code>for var = </code> loop:<langsyntaxhighlight lang="lisp">(loop for x = 0 then y and y = 1 then (+ x y) do (print x))</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="lisp">(defun fibonacci-recursive (n)
(if (< n 2)
n
(+ (fibonacci-recursive (- n 2)) (fibonacci-recursive (- n 1)))))</langsyntaxhighlight>
 
 
<langsyntaxhighlight lang="lisp">(defun fibonacci-tail-recursive ( n &optional (a 0) (b 1))
(if (= n 0)
a
(fibonacci-tail-recursive (- n 1) b (+ a b))))</langsyntaxhighlight>
 
Tail recursive and squaring:
<langsyntaxhighlight lang="lisp">(defun fib (n &optional (a 1) (b 0) (p 0) (q 1))
(if (= n 1) (+ (* b p) (* a q))
(fib (ash n -1)
Line 3,182 ⟶ 4,647:
(+ (* q q) (* 2 p q))))) ;p is Fib(2^n-1), q is Fib(2^n).
 
(print (fib 100000))</langsyntaxhighlight>
=== Alternate solution ===
I use [https://franz.com/downloads/clp/survey Allegro CL 10.1]
 
<langsyntaxhighlight lang="lisp">
;; Project : Fibonacci sequence
 
Line 3,200 ⟶ 4,665:
(write(+ n 1)) (format t "~a" ": ")
(write (fibonacci n)) (terpri))
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,217 ⟶ 4,682:
 
=== Solution with methods and eql specializers ===
<langsyntaxhighlight lang="lisp">
(defmethod fib (n)
(declare ((integer 0 *) n))
Line 3,226 ⟶ 4,691:
 
(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.
<langsyntaxhighlight lang="lisp">(defun fibo (n)
(cond ((< n 0) nil)
((< n 2) n)
Line 3,239 ⟶ 4,704:
(second leo))
leo))
finally (return (first leo)))))))</langsyntaxhighlight>
 
{{out}}
Line 3,271 ⟶ 4,736:
we reverse it back when we return it).
 
<langsyntaxhighlight lang="lisp">(defparameter *fibo-start* '(1 1)) ; elements 1 and 2
 
;;; Helper functions
Line 3,303 ⟶ 4,768:
(fibo (1+ lower))
(fibo lower))
(1+ (- upper lower))))))</langsyntaxhighlight>
{{out}}
<pre>> (fibo 100)
Line 3,318 ⟶ 4,783:
=={{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.
<langsyntaxhighlight lang="czasm">loop: LDA y ; higher No.
STA temp
ADD x ; lower No.
Line 3,339 ⟶ 4,804:
x: 1
y: 1
temp: 0</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="corescript">print Fibonacci Sequence:
var previous = 1
var number = 0
Line 3,356 ⟶ 4,833:
 
:kill
stop</langsyntaxhighlight>
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
 
sub fibonacci(n: uint32): (a: uint32) is
Line 3,379 ⟶ 4,856:
i := i + 1;
end loop;
print_nl();</langsyntaxhighlight>
 
{{out}}
Line 3,386 ⟶ 4,863:
 
=={{header|Crystal}}==
 
===Recursive===
<langsyntaxhighlight lang="ruby">def fib(n)
n < 2 ? n : fib(n - 1) + fib(n - 2)
end</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight lang="ruby">def fibIterative(n, prevFib = 0, fib = 1)
return n if n < 2
 
Line 3,401 ⟶ 4,877:
 
prevFib
end</langsyntaxhighlight>
 
===Tail Recursive===
<langsyntaxhighlight lang="ruby">def fibTailRecursive(n, prevFib = 0, fib = 1)
n == 0 ? prevFib : fibTailRecursive(n - 1, fib, prevFib + fib)
end</langsyntaxhighlight>
 
===Analytic===
<langsyntaxhighlight lang="ruby">def fibBinet(n)
(((5 ** 0.5 + 1) / 2) ** n / 5 ** 0.5).round.to_i
end</langsyntaxhighlight>
 
=={{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.
All functions have support for negative arguments.
<langsyntaxhighlight lang="d">import std.stdio, std.conv, std.algorithm, std.math;
 
long sgn(alias unsignedFib)(int n) { // break sign manipulation apart
Line 3,504 ⟶ 4,980:
foreach (i, f; fibG(-9))
writef("%d:%d | ", i, f);
}</langsyntaxhighlight>
{{out}} for n = 85:
<pre>Fib( 85) =
Line 3,512 ⟶ 4,988:
0:0 | -1:1 | -2:-1 | -3:2 | -4:-3 | -5:5 | -6:-8 | -7:13 | -8:-21 | -9:34 | </pre>
===Matrix Exponentiation Version===
<langsyntaxhighlight lang="d">import std.bigint;
 
T fibonacciMatrix(T=BigInt)(size_t n) {
Line 3,541 ⟶ 5,017:
void main() {
10_000_000.fibonacciMatrix;
}</langsyntaxhighlight>
 
===Faster Version===
For N = 10_000_000 this is about twice faster (run-time about 2.20 seconds) than the matrix exponentiation version.
<langsyntaxhighlight lang="d">import std.bigint, std.math;
 
// Algorithm from: Takahashi, Daisuke,
Line 3,588 ⟶ 5,064:
void main() {
10_000_000.fibonacci;
}</langsyntaxhighlight>
 
=={{header|Dart}}==
<langsyntaxhighlight lang="dart">int fib(int n) {
if (n==0 || n==1) {
return n;
Line 3,610 ⟶ 5,086:
print(fib(11));
print(fibRec(11));
}</langsyntaxhighlight>
=={{header|Datalog}}==
Simple recurive implementation for Souffle.
<langsyntaxhighlight 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.</langsyntaxhighlight>
 
=={{header|DBL}}==
<langsyntaxhighlight lang="dart">;
; Fibonacci sequence for DBL version 4 by Dario B.
;
Line 3,654 ⟶ 5,130:
CLOSE 1
END</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="dc">[ # todo: n(<2) -- 1 and break 2 levels
d - # 0
1 + # 1
Line 3,675 ⟶ 5,151:
] sF
 
33 lF x f</langsyntaxhighlight>
{{out}}
<pre>
Line 3,684 ⟶ 5,160:
 
=== Iterative ===
<syntaxhighlight lang="delphi">
<lang Delphi>
function FibonacciI(N: Word): UInt64;
var
Line 3,703 ⟶ 5,179:
end;
end;
</syntaxhighlight>
</lang>
 
=== Recursive ===
<syntaxhighlight lang="delphi">
<lang Delphi>
function Fibonacci(N: Word): UInt64;
begin
Line 3,714 ⟶ 5,190:
Result := Fibonacci(N - 1) + Fibonacci(N - 2);
end;
</syntaxhighlight>
</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>.
<syntaxhighlight lang="delphi">
<lang Delphi>
function fib(n: Int64): Int64;
 
Line 3,756 ⟶ 5,232:
fib := matrix[0,0];
end;
</syntaxhighlight>
</lang>
 
=={{header|DIBOL-11}}==
<syntaxhighlight lang="dibol-11">
<lang DIBOL-11>
 
; START Redone ;Firstto include the first 10two Fibonaccivalues NUmbersthat
; are noot computed.
 
START ;First 15 Fibonacci NUmbers
 
 
Line 3,768 ⟶ 5,247:
FIB2, D10, 1
FIBNEW, D10
LOOPCNT, D2, 13
 
RECORD HEADER
, A32, "First 1015 Fibonacci Numbers."
 
RECORD OUTPUT
Line 3,784 ⟶ 5,263:
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
Line 3,795 ⟶ 5,285:
LOOPCNT = LOOPCNT + 1
IF LOOPCNT .LE. 1015 GOTO LOOP
 
CLOSE 8
END
 
 
 
</syntaxhighlight>
</lang>
 
=={{header|DWScript}}==
 
<langsyntaxhighlight Delphilang="delphi">function fib(N : Integer) : Integer;
begin
if N < 2 then Result := 1
else Result := fib(N-2) + fib(N-1);
End;</langsyntaxhighlight>
 
=={{header|Dyalect}}==
 
<langsyntaxhighlight Dyalectlang="dyalect">func fib(n) {
if n < 2 {
return n
Line 3,821 ⟶ 5,313:
}
 
print(fib(30))</langsyntaxhighlight>
 
=={{header|E}}==
<langsyntaxhighlight lang="e">def fib(n) {
var s := [0, 1]
for _ in 0..!n {
Line 3,831 ⟶ 5,323:
}
return s[0]
}</langsyntaxhighlight>
 
(This version defines <tt>fib(0) = 0</tt> because [http://www.research.att.com/~njas/sequences/A000045 OEIS A000045] does.)
Line 3,837 ⟶ 5,329:
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">
<lang>func fib n . res .
func iffib n < 2.
if resn =< n2
return n
.
prev = 0.
val prev = 10
for _val range n -= 1
for resi = prev2 +to valn
prev h = prev + val
val prev = resval
val = h
.
.
return val
.
callprint fib 36 r
</syntaxhighlight>
print r</lang>
 
Recursive (inefficient):
 
<syntaxhighlight lang="text">
<lang>func fib n . res .
func iffib n < 2.
if resn =< n2
return n
else
.
call fib n - 1 a
callreturn fib (n - 2) b+ fib (n - 1)
res = a + b
.
.
callprint fib 36 r
</syntaxhighlight>
print r</lang>
 
=={{header|EchoLisp}}==
Use '''memoization''' with the recursive version.
<langsyntaxhighlight lang="scheme">
(define (fib n)
(if (< n 2) n
Line 3,877 ⟶ 5,369:
(for ((i 12)) (write (fib i)))
0 1 1 2 3 5 8 13 21 34 55 89
</syntaxhighlight>
</lang>
 
=={{header|ECL}}==
Line 3,883 ⟶ 5,375:
===Analytic===
 
<langsyntaxhighlight ECLlang="ecl">//Calculates Fibonacci sequence up to n steps using Binet's closed form solution
 
 
Line 3,911 ⟶ 5,403:
RETURN FibSeq;
END; }</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="edsac">[ Fibonacci sequence
==================
Line 3,966 ⟶ 5,458:
[ 20 ] P0F [ used to clear a ]
 
EZPF [ begin execution ]</langsyntaxhighlight>
{{out}}
<pre>00000000000110111</pre>
 
=={{header|Eiffel}}==
<langsyntaxhighlight lang="eiffel">
class
APPLICATION
Line 4,022 ⟶ 5,514:
 
end
</syntaxhighlight>
</lang>
 
=={{header|Ela}}==
Tail-recursive function:
<langsyntaxhighlight Elalang="ela">fib = fib' 0 1
where fib' a b 0 = a
fib' a b n = fib' b (a + b) (n - 1)</langsyntaxhighlight>
Infinite (lazy) list:
<langsyntaxhighlight Elalang="ela">fib = fib' 1 1
where fib' x y = & x :: fib' y (x + y)</langsyntaxhighlight>
 
=={{header|Elena}}==
{{trans|Smalltalk}}
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import extensions;
fibu(n)
Line 4,047 ⟶ 5,539:
else
{
for(int i := 2,; i <= n,; i+=1)
{
int t := ac[1];
Line 4,060 ⟶ 5,552:
public program()
{
for(int i := 0,; i <= 10,; i+=1)
{
console.printLine(fibu(i))
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,081 ⟶ 5,573:
=== Alternative version using yieldable method ===
 
<langsyntaxhighlight lang="elena">import extensions;
 
public FibonacciGenerator
Line 4,090 ⟶ 5,582:
long n_1 := 1l;
 
$yield: n_2;
$yield: n_1;
 
while(true)
Line 4,097 ⟶ 5,589:
long n := n_2 + n_1;
 
$yield: n;
 
n_2 := n_1;
Line 4,109 ⟶ 5,601:
auto e := new FibonacciGenerator();
for(int i := 0,; i < 10,; i += 1) {
console.printLine(e.next())
};
console.readChar()
}</langsyntaxhighlight>
 
=={{header|Elixir}}==
<langsyntaxhighlight Elixirlang="elixir">defmodule Fibonacci do
def fib(0), do: 0
def fib(1), do: 1
Line 4,129 ⟶ 5,621:
end
 
IO.inspect Enum.map(0..10, fn i-> Fibonacci.fib(i) end)</langsyntaxhighlight>
 
Using Stream:
<syntaxhighlight lang="elixir">
<lang Elixir>
Stream.unfold({0,1}, fn {a,b} -> {a,{b,a+b}} end) |> Enum.take(10)
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,142 ⟶ 5,634:
 
=={{header|Elm}}==
 
Naïve recursive implementation.
<langsyntaxhighlight lang="haskell">fibonacci : Int -> Int
fibonacci n = if n < 2 then
n
else
fibonacci(n - 2) + fibonacci(n - 1)</langsyntaxhighlight>
 
 
'''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}}==
Line 4,153 ⟶ 5,670:
===version 1===
 
<langsyntaxhighlight Lisplang="lisp">(defun fib (n a b c)
(cond
((< c n) (fib n b (+ a b) (+ 1 c)))
Line 4,162 ⟶ 5,679:
(if (< n 2)
n
(fib n 0 1 1)))</langsyntaxhighlight>
 
===version 2===
 
<langsyntaxhighlight Lisplang="lisp">(defun fibonacci (n)
(let (vec i j k)
(if (< n 2)
Line 4,180 ⟶ 5,697:
j (1+ j)
k (1+ k)))
(elt vec n))))</langsyntaxhighlight>
 
<b>Eval:</b>
 
<langsyntaxhighlight Lisplang="lisp">(insert
(mapconcat (lambda (n) (format "%d" (fibonacci n)))
(number-sequence 0 15) " "))</langsyntaxhighlight>
 
{{out}}
Line 4,194 ⟶ 5,711:
=={{header|Erlang}}==
===Recursive ===
<syntaxhighlight lang="erlang">
<lang Erlang>
-module(fib).
-export([fib/1]).
Line 4,201 ⟶ 5,718:
fib(1) -> 1;
fib(N) -> fib(N-1) + fib(N-2).
</syntaxhighlight>
</lang>
 
===Iterative ===
<syntaxhighlight lang="erlang">
<lang Erlang>
-module(fiblin).
-export([fib/1])
Line 4,218 ⟶ 5,735:
fib(N, A, B) -> if N < 1 -> B; true -> fib(N-1, B, A+B) end.
 
</syntaxhighlight>
</lang>
 
<b> Evaluate:</b>
<syntaxhighlight lang="erlang">
<lang Erlang>
io:write([fiblin:fib(X) || X <- lists:seq(1,10) ]).
</syntaxhighlight>
</lang>
 
<b> Output:</b>
Line 4,231 ⟶ 5,748:
 
===Iterative 2===
<syntaxhighlight lang="erlang">
<lang Erlang>
fib(N) -> fib(N, 0, 1).
 
Line 4,237 ⟶ 5,754:
fib(Iter, Result, Next) -> fib(Iter-1, Next, Result+Next).
 
</syntaxhighlight>
</lang>
 
=={{header|ERRE}}==
<langsyntaxhighlight ERRElang="erre">!-------------------------------------------
! derived from my book "PROGRAMMARE IN ERRE"
! iterative solution
Line 4,267 ⟶ 5,784:
 
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,277 ⟶ 5,794:
==='Recursive' version===
{{works with|Euphoria|any version}}
<syntaxhighlight lang="euphoria">
<lang Euphoria>
function fibor(integer n)
if n<2 then return n end if
return fibor(n-1)+fibor(n-2)
end function
</syntaxhighlight>
</lang>
 
==='Iterative' version===
{{works with|Euphoria|any version}}
<syntaxhighlight lang="euphoria">
<lang Euphoria>
function fiboi(integer n)
integer f0=0, f1=1, f
Line 4,297 ⟶ 5,814:
return f
end function
</syntaxhighlight>
</lang>
 
==='Tail recursive' version===
{{works with|Euphoria|4.0.0}}
<syntaxhighlight lang="euphoria">
<lang Euphoria>
function fibot(integer n, integer u = 1, integer s = 0)
if n < 1 then
Line 4,312 ⟶ 5,829:
-- example:
? fibot(10) -- says 55
</syntaxhighlight>
</lang>
 
==='Paper tape' version===
{{works with|Euphoria|4.0.0}}
<syntaxhighlight lang="euphoria">
<lang Euphoria>
include std/mathcons.e -- for PINF constant
 
Line 4,396 ⟶ 5,913:
end while
 
</syntaxhighlight>
</lang>
 
=={{header|Excel}}==
Line 4,405 ⟶ 5,922:
 
{{Works with|Office 365 Betas 2021}}
<langsyntaxhighlight lang="lisp">FIBONACCI
=LAMBDA(n,
APPLYN(n - 2)(
Line 4,416 ⟶ 5,933:
)
)({1;1})
)</langsyntaxhighlight>
 
And assuming that the following names are also bound to reusable generic lambdas in the Name manager:
<langsyntaxhighlight lang="lisp">APPENDROWS
=LAMBDA(xs,
LAMBDA(ys,
Line 4,475 ⟶ 5,992:
)
)
)</langsyntaxhighlight>
 
{{Out}}
Line 4,543 ⟶ 6,060:
Or as a fold, obtaining just the Nth term of the Fibonacci series:
 
<langsyntaxhighlight lang="lisp">FIBONACCI2
=LAMBDA(n,
INDEX(
Line 4,557 ⟶ 6,074:
1
)
)</langsyntaxhighlight>
 
Assuming the following generic bindings in the Excel worksheet Name manager:
 
<langsyntaxhighlight lang="lisp">APPEND
=LAMBDA(xs,
LAMBDA(ys,
Line 4,621 ⟶ 6,138:
SEQUENCE(1, COLUMNS(xs))
)
)</langsyntaxhighlight>
{{Out}}
{| class="wikitable"
Line 4,647 ⟶ 6,164:
=={{header|F_Sharp|F#}}==
This is a fast [tail-recursive] approach using the F# big integer support:
<langsyntaxhighlight lang="fsharp">
let fibonacci n : bigint =
let rec f a b n =
Line 4,656 ⟶ 6,173:
f (bigint 0) (bigint 1) n
> fibonacci 100;;
val it : bigint = 354224848179261915075I</langsyntaxhighlight>
Lazy evaluated using sequence workflow:
<langsyntaxhighlight lang="fsharp">let rec fib = seq { yield! [0;1];
for (a,b) in Seq.zip fib (Seq.skip 1 fib) -> a+b}</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="fsharp">let fibonacci = Seq.unfold (fun (x, y) -> Some(x, (y, x + y))) (0I,1I)
fibonacci |> Seq.nth 10000
</syntaxhighlight>
</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.
<langsyntaxhighlight lang="fsharp">
open System
open System.Diagnostics
Line 4,715 ⟶ 6,232:
iter1 1 1I 1I 0I
|> iter2
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
===Iterative===
<langsyntaxhighlight lang="factor">: fib ( n -- m )
dup 2 < [
[ 0 1 ] dip [ swap [ + ] keep ] times
drop
] unless ;</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="factor">: fib ( n -- m )
dup 2 < [
[ 1 - fib ] [ 2 - fib ] bi +
] unless ;</langsyntaxhighlight>
 
===Tail-Recursive===
<langsyntaxhighlight lang="factor">: fib2 ( x y n -- a )
dup 1 <
[ 2drop ]
[ [ swap [ + ] keep ] dip 1 - fib2 ]
if ;
: fib ( n -- m ) [ 0 1 ] dip fib2 ;</langsyntaxhighlight>
 
===Matrix===
{{trans|Ruby}}
<langsyntaxhighlight lang="factor">USE: math.matrices
 
: fib ( n -- m )
Line 4,747 ⟶ 6,264:
[ { { 0 1 } { 1 1 } } ] dip 1 - m^n
second second
] unless ;</langsyntaxhighlight>
 
=={{header|Falcon}}==
===Iterative===
<langsyntaxhighlight lang="falcon">function fib_i(n)
 
if n < 2: return n
Line 4,763 ⟶ 6,280:
end
return fib
end</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight lang="falcon">function fib_r(n)
if n < 2 : return n
return fib_r(n-1) + fib_r(n-2)
end</langsyntaxhighlight>
===Tail Recursive===
<langsyntaxhighlight lang="falcon">function fib_tr(n)
return fib_aux(n,0,1)
end
Line 4,778 ⟶ 6,295:
default: return fib_aux(n-1,a+b,a)
end
end</langsyntaxhighlight>
 
=={{header|FALSE}}==
<langsyntaxhighlight lang="false">[[$0=~][1-@@\$@@+\$44,.@]#]f:
20n: {First 20 numbers}
0 1 n;f;!%%44,. {Output: "0,1,1,2,3,5..."}</langsyntaxhighlight>
 
=={{header|Fancy}}==
<langsyntaxhighlight lang="fancy">class Fixnum {
def fib {
match self -> {
Line 4,799 ⟶ 6,316:
x fib println
}
</syntaxhighlight>
</lang>
 
=={{header|Fantom}}==
Line 4,805 ⟶ 6,322:
Ints have a limit of 64-bits, so overflow errors occur after computing Fib(92) = 7540113804746346429.
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 4,827 ⟶ 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}}==
<langsyntaxhighlight 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;
Line 4,840 ⟶ 6,377:
fi;
fi;
.</langsyntaxhighlight>
 
=={{header|Fexl}}==
 
<syntaxhighlight lang="fexl">
<lang Fexl>
# (fib n) = the nth Fibonacci number
\fib=
Line 4,861 ⟶ 6,398:
# Now test it:
for 0 20 (\n say (fib n))
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,890 ⟶ 6,427:
=={{header|Fish}}==
Outputs Fibonacci numbers until stopped.
<langsyntaxhighlight Fishlang="fish">10::n' 'o&+&$10.</langsyntaxhighlight>
 
=={{header|FOCAL}}==
<langsyntaxhighlight lang="focal">01.10 TYPE "FIBONACCI NUMBERS" !
01.20 ASK "N =", N
01.30 SET A=0
Line 4,903 ⟶ 6,440:
02.10 SET T=B
02.20 SET B=A+B
02.30 SET A=T</langsyntaxhighlight>
{{out}}
<pre>FIBONACCI NUMBERS
Line 4,910 ⟶ 6,447:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: fib ( n -- fib )
0 1 rot 0 ?do over + swap loop drop ;</langsyntaxhighlight>
 
Or, for negative-index support:
 
<langsyntaxhighlight 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 ;</langsyntaxhighlight>
 
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.)
 
<langsyntaxhighlight lang="forth">: F-start, here 1 0 dup , ;
: F-next, over + swap
dup 0> IF dup , true ELSE false THEN ;
Line 4,939 ⟶ 6,476:
16 fibonacci . 987 ok
#F/64 . 93 ok
92 fibonacci . 7540113804746346429 ok \ largest number generated.</langsyntaxhighlight>
 
=={{header|Fortran}}==
===FORTRAN IV===
<langsyntaxhighlight lang="fortran">C FIBONACCI SEQUENCE - FORTRAN IV
NN=46
DO 1 I=0,NN
Line 4,964 ⟶ 6,501:
5 IFN=IFNM1+IFNM2
9 IFIBO=IFN
END</langsyntaxhighlight>
{{out}}
<pre>
Line 4,983 ⟶ 6,520:
</pre>
===FORTRAN 77===
<langsyntaxhighlight lang="fortran">
FUNCTION IFIB(N)
IF (N.EQ.0) THEN
Line 5,008 ⟶ 6,545:
IFIB=ITEMP0
END
</syntaxhighlight>
</lang>
Test program
<langsyntaxhighlight lang="fortran">
EXTERNAL IFIB
CHARACTER*10 LINE
Line 5,022 ⟶ 6,559:
901 FORMAT(3(X,I10))
END
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,042 ⟶ 6,579:
===Recursive===
In ISO Fortran 90 or later, use a RECURSIVE function:
<langsyntaxhighlight lang="fortran">module fibonacci
contains
recursive function fibR(n) result(fib)
Line 5,053 ⟶ 6,590:
case default; fib = fibR(n-1) + fibR(n-2)
end select
end function fibR</langsyntaxhighlight>
===Iterative===
In ISO Fortran 90 or later:
<langsyntaxhighlight lang="fortran"> function fibI(n)
integer, intent(in) :: n
integer, parameter :: fib0 = 0, fib1 = 1
Line 5,075 ⟶ 6,612:
end select
end function fibI
end module fibonacci</langsyntaxhighlight>
 
Test program
<langsyntaxhighlight lang="fortran">program fibTest
use fibonacci
Line 5,084 ⟶ 6,621:
print *, fibr(i), fibi(i)
end do
end program fibTest</langsyntaxhighlight>
 
{{out}}
Line 5,103 ⟶ 6,640:
=={{header|Free Pascal}}==
''See also: [[#Pascal|Pascal]]''
<syntaxhighlight lang="pascal">type
<lang Pascal>type
/// domain for Fibonacci function
/// where result is within nativeUInt
Line 5,142 ⟶ 6,679:
// assign to previous, bc f[current] = f[next] for next iteration
fibonacci := f[previous];
end;</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
Extended sequence coded big integer.
<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</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}}==
All of Frink's integers can be arbitrarily large.
<langsyntaxhighlight lang="frink">
fibonacciN[n] :=
{
Line 5,264 ⟶ 6,696:
return a
}
</syntaxhighlight>
</lang>
 
=={{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.
<langsyntaxhighlight lang="friscasm">FIBONACCI PUSH R1
PUSH R2
PUSH R3
Line 5,290 ⟶ 6,722:
POP R1
 
RET</langsyntaxhighlight>
 
=={{header|FunL}}==
=== Recursive ===
<langsyntaxhighlight lang="funl">def
fib( 0 ) = 0
fib( 1 ) = 1
fib( n ) = fib( n - 1 ) + fib( n - 2 )</langsyntaxhighlight>
 
=== Tail Recursive ===
<langsyntaxhighlight lang="funl">def fib( n ) =
def
_fib( 0, prev, _ ) = prev
Line 5,306 ⟶ 6,738:
_fib( n, prev, next ) = _fib( n - 1, next, next + prev )
 
_fib( n, 0, 1 )</langsyntaxhighlight>
 
=== Lazy List ===
<langsyntaxhighlight lang="funl">val fib =
def _fib( a, b ) = a # _fib( b, a + b )
 
_fib( 0, 1 )
 
println( fib(10000) )</langsyntaxhighlight>
 
{{out}}
Line 5,323 ⟶ 6,755:
 
=== Iterative ===
<langsyntaxhighlight lang="funl">def fib( n ) =
a, b = 0, 1
 
Line 5,329 ⟶ 6,761:
a, b = b, a+b
 
a</langsyntaxhighlight>
 
=== Binet's Formula ===
<langsyntaxhighlight lang="funl">import math.sqrt
 
def fib( n ) =
phi = (1 + sqrt( 5 ))/2
int( (phi^n - (-phi)^-n)/sqrt(5) + .5 )</langsyntaxhighlight>
 
=== Matrix Exponentiation ===
<langsyntaxhighlight lang="funl">def mul( a, b ) =
res = array( a.length(), b(0).length() )
 
Line 5,357 ⟶ 6,789:
 
for i <- 0..10
println( fib(i) )</langsyntaxhighlight>
 
{{out}}
Line 5,379 ⟶ 6,811:
=== Iterative ===
 
<syntaxhighlight lang="futhark">
<lang Futhark>
fun main(n: int): int =
loop((a,b) = (0,1)) = for _i < n do
(b, a + b)
in a
</syntaxhighlight>
</lang>
 
=={{header|FutureBasic}}==
=== Iterative ===
<langsyntaxhighlight lang="futurebasic">window 1, @"Fibonacci Sequence", (0,0,480,620)
 
local fn Fibonacci( n as long ) as long
Line 5,417 ⟶ 6,849:
print : printf @"Compute time: %.3f ms",(fn CACurrentMediaTime-t)*1000
 
HandleEvents</langsyntaxhighlight>
Output:
<pre>
Line 5,463 ⟶ 6,895:
 
Compute time: 2.143 ms</pre>
 
=== Recursive ===
Cost is a time penalty
<syntaxhighlight lang="futurebasic">
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
</syntaxhighlight>
{{output}}
<pre>
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
</pre>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Fibonacci_numbers}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
=== 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]]
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
[[File:Fōrmulæ - Fibonacci sequence result.png]]
In '''[https://formulae.org/?example=Fibonacci_numbers this]''' page you can see the program(s) related to this task and their results.
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">fib := function(n)
local a;
a := [[0, 1], [1, 1]]^n;
return a[1][2];
end;</langsyntaxhighlight>
GAP has also a buit-in function for that.
<syntaxhighlight lang ="gap">Fibonacci(n);</langsyntaxhighlight>
 
=={{header|Gecho}}==
<langsyntaxhighlight lang="gecho">0 1 dup wover + dup wover + dup wover + dup wover +</langsyntaxhighlight>
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}}==
<syntaxhighlight lang="gml">///fibonacci(n)
 
<lang gml>///fibonacci(n)
//Returns the nth fibonacci number
 
Line 5,553 ⟶ 7,085:
}
 
return numb;</langsyntaxhighlight>
 
=={{header|Go}}==
=== Recursive ===
<langsyntaxhighlight lang="go">func fib(a int) int {
if a < 2 {
return a
}
return fib(a - 1) + fib(a - 2)
}</langsyntaxhighlight>
=== Iterative ===
<langsyntaxhighlight lang="go">import (
"math/big"
)
Line 5,578 ⟶ 7,110:
}
return b
}</langsyntaxhighlight>
=== Iterative using a closure ===
<langsyntaxhighlight lang="go">func fibNumber() func() int {
fib1, fib2 := 0, 1
return func() int {
Line 5,595 ⟶ 7,127:
}
return fib
}</langsyntaxhighlight>
=== Using a goroutine and channel ===
<langsyntaxhighlight lang="go">func fib(c chan int) {
a, b := 0, 1
for {
Line 5,612 ⟶ 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}}==
Line 5,618 ⟶ 7,216:
=== Recursive ===
A recursive closure must be ''pre-declared''.
<langsyntaxhighlight lang="groovy">def rFib
rFib = {
it == 0 ? 0
Line 5,625 ⟶ 7,223:
/*it < 0*/: rFib(it+2) - rFib(it+1)
}</langsyntaxhighlight>
 
=== Iterative ===
<langsyntaxhighlight lang="groovy">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]
}</langsyntaxhighlight>
 
=== Analytic ===
<langsyntaxhighlight lang="groovy">final φ = (1 + 5**(1/2))/2
def aFib = { (φ**it - (-φ)**(-it))/(5**(1/2)) as BigInteger }</langsyntaxhighlight>
 
Test program:
<langsyntaxhighlight lang="groovy">def time = { Closure c ->
def start = System.currentTimeMillis()
def result = c()
Line 5,655 ⟶ 7,253:
fibList.each { printf ' %3d', it }
println()
}</langsyntaxhighlight>
 
{{out}}
Line 5,666 ⟶ 7,264:
=={{header|Harbour}}==
===Recursive===
<syntaxhighlight lang="harbour">
<lang Harbour>
#include "harbour.ch"
Function fibb(a,b,n)
return(if(--n>0,fibb(b,a+b,n),a))
</syntaxhighlight>
</lang>
 
===Iterative===
<syntaxhighlight lang="harbour">
<lang Harbour>
#include "harbour.ch"
Function fibb(n)
Line 5,683 ⟶ 7,281:
end while
return(fnext)
</syntaxhighlight>
</lang>
 
=={{header|Haskell}}==
Line 5,689 ⟶ 7,287:
{{Works with|exact-real|0.12.5.1}}
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'''.
<langsyntaxhighlight lang="haskell">
import Data.CReal
 
Line 5,696 ⟶ 7,294:
fib :: (Integral b) => b -> CReal 0
fib n = (phi^^n - (-phi)^^(-n))/sqrt 5
</syntaxhighlight>
</lang>
Let's try it for large numbers:
<langsyntaxhighlight lang="haskell">
λ> fib 10 :: CReal 0
55
Line 5,711 ⟶ 7,309:
-55
(0.01 secs, 138,408 bytes)
</syntaxhighlight>
</lang>
 
===Recursive===
Simple definition, very inefficient.
 
<langsyntaxhighlight lang="haskell">fib x =
if x < 1
then 0
else if x < 2
then 1
else fib (x - 1) + fib (x - 2)</langsyntaxhighlight>
 
===Recursive with Memoization===
Very fast.
<langsyntaxhighlight lang="haskell">fib x =
if x < 1
then 0
Line 5,732 ⟶ 7,330:
else fibs !! (x - 1) + fibs !! (x - 2)
where
fibs = map fib [0 ..]</langsyntaxhighlight>
 
===Recursive with Memoization using memoized library===
Even faster and simpler is to use a defined memoizer (e.g. from MemoTrie package):
<langsyntaxhighlight lang="haskell">import Data.MemoTrie
fib :: Integer -> Integer
fib = memo f where
f 0 = 0
f 1 = 1
f n = fib (n-1) + fib (n-2)</langsyntaxhighlight>
You can rewrite this without introducing f explicitly
<langsyntaxhighlight lang="haskell">import Data.MemoTrie
fib :: Integer -> Integer
fib = memo $ \x -> case x of
0 -> 0
1 -> 1
n -> fib (n-1) + fib (n-2)</langsyntaxhighlight>
Or using LambdaCase extension you can write it even shorter:
<langsyntaxhighlight lang="haskell">{-# Language LambdaCase #-}
import Data.MemoTrie
fib :: Integer -> Integer
Line 5,756 ⟶ 7,354:
0 -> 0
1 -> 1
n -> fib (n-1) + fib (n-2)</langsyntaxhighlight>
The version that supports negative numbers:
<langsyntaxhighlight lang="haskell">{-# Language LambdaCase #-}
import Data.MemoTrie
fib :: Integer -> Integer
Line 5,765 ⟶ 7,363:
1 -> 1
n | n>0 -> fib (n-1) + fib (n-2)
| otherwise -> fib (n+2) - fib (n+1)</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight lang="haskell">fib n = go n 0 1
where
go n a b
| n == 0 = a
| otherwise = go (n - 1) b (a + b)</langsyntaxhighlight>
 
==== With lazy lists ====
This is a standard example how to use lazy lists. Here's the (infinite) list of all Fibonacci numbers:
 
<langsyntaxhighlight lang="haskell">fib = 0 : 1 : zipWith (+) fib (tail fib)</langsyntaxhighlight>
Or alternatively:
<langsyntaxhighlight lang="haskell">fib = 0 : 1 : (zipWith (+) <*> tail) fib </langsyntaxhighlight>
 
The ''n''th Fibonacci number is then just <code plang="haskell">fib !! n</code>. The above is equivalent to
 
<langsyntaxhighlight lang="haskell">fib = 0 : 1 : next fib where next (a: t@(b:_)) = (a+b) : next t</langsyntaxhighlight>
 
Also
 
<langsyntaxhighlight lang="haskell">fib = 0 : scanl (+) 1 fib</langsyntaxhighlight>
 
==== As a fold ====
Accumulator holds last two members of the series:
 
<langsyntaxhighlight lang="haskell">import Data.List (foldl') --'
 
fib :: Integer -> Integer
Line 5,800 ⟶ 7,398:
(\(a, b) _ -> (b, a + b))
(0, 1)
[1 .. n]</langsyntaxhighlight>
 
=== With matrix exponentiation ===
Line 5,806 ⟶ 7,404:
we can simply write:
 
<langsyntaxhighlight lang="haskell">import Data.List (transpose)
 
fib
Line 5,849 ⟶ 7,447:
-- TEST ----------------------------------------------------------------------
main :: IO ()
main = (print . take 10 . show . fib) (10 ^ 5)</langsyntaxhighlight>
 
So, for example, the hundred-thousandth Fibonacci number starts with the digits:
Line 5,857 ⟶ 7,455:
=== With recurrence relations ===
Using <code>Fib[m=3n+r]</code> [http://en.wikipedia.org/wiki/Fibonacci_number#Other_identities recurrence identities]:
<langsyntaxhighlight lang="haskell">import Control.Arrow ((&&&))
 
fibstep :: (Integer, Integer) -> (Integer, Integer)
Line 5,891 ⟶ 7,489:
 
main :: IO ()
main = print $ (length &&& take 20) . show . fst $ fibN2 (10 ^ 2)</langsyntaxhighlight>
{{Out}}
<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>:
<langsyntaxhighlight lang="haskell"> *Main> (length &&& take 20) . show . fst $ fibN2 (10^6)
(208988,"19532821287077577316")</langsyntaxhighlight>
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
 
<langsyntaxhighlight 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</langsyntaxhighlight>
 
and for <i>(n,n+1) ---> (2n,2n+1)</i> (derived from d'Ocagne's identity, for example),
 
<langsyntaxhighlight 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</langsyntaxhighlight>
 
=={{header|Haxe}}==
=== Iterative ===
 
<langsyntaxhighlight lang="haxe">static function fib(steps:Int, handler:Int->Void)
{
var current = 0;
Line 5,925 ⟶ 7,523:
}
handler(current);
}</langsyntaxhighlight>
 
=== As Iterator ===
<langsyntaxhighlight lang="haxe">class FibIter
{
private var current = 0;
Line 5,946 ⟶ 7,544:
return ret;
}
}</langsyntaxhighlight>
 
Used like:
<langsyntaxhighlight lang="haxe">for (i in new FibIter(10))
Sys.println(i);</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">REAL :: Fibonacci(10)
 
Fibonacci = ($==2) + Fibonacci($-1) + Fibonacci($-2)
WRITE(ClipBoard) Fibonacci ! 0 1 1 2 3 5 8 13 21 34</langsyntaxhighlight>
 
=={{header|Hoon}}==
<langsyntaxhighlight lang="hoon">|= n=@ud
=/ a=@ud 0
=/ b=@ud 1
|-
?: =(n 0) a
$(a b, b (add a b), n (dec n))</langsyntaxhighlight>
 
=={{header|Hope}}==
===Recursive===
<langsyntaxhighlight lang="hope">dec f : num -> num;
--- f 0 <= 0;
--- f 1 <= 1;
--- f(n+2) <= f n + f(n+1);</langsyntaxhighlight>
 
===Tail-recursive===
<langsyntaxhighlight lang="hope">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;</langsyntaxhighlight>
 
=== With lazy lists ===
This language, being one of Haskell's ancestors, also has lazy lists. Here's the (infinite) list of all Fibonacci numbers:
<langsyntaxhighlight lang="hope">dec fibs : list num;
--- fibs <= fs whererec fs == 0::1::map (+) (tail fs||fs);</langsyntaxhighlight>
The ''n''th Fibonacci number is then just <code plang="hope">fibs @ n</code>.
 
=={{header|Hy}}==
Recursive implementation.
<langsyntaxhighlight lang="clojure">(defn fib [n]
(if (< n 2)
n
(+ (fib (- n 2)) (fib (- n 1)))))</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 5,996 ⟶ 7,594:
computes fib(1000) if there is no integer argument.
 
<langsyntaxhighlight Iconlang="icon">procedure main(args)
write(fib(integer(!args) | 1000)
end
Line 6,009 ⟶ 7,607:
/fCache[n] := fib(n-1) + fib(n-2)
return fCache[n]
end</langsyntaxhighlight>
{{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]
Line 6,018 ⟶ 7,616:
This example computes fib(1000000) if there is no integer argument.
 
<langsyntaxhighlight Iconlang="icon">procedure main(args)
write(fib(integer(!args) | 1000000))
end
Line 6,034 ⟶ 7,632:
if n%2 = 1 then return [c+d, d]
else return [d, c]
end</langsyntaxhighlight>
 
=={{header|IDL}}==
===Recursive===
<langsyntaxhighlight lang="idl">function fib,n
if n lt 3 then return,1L else return, fib(n-1)+fib(n-2)
end</langsyntaxhighlight>
 
Execution time O(2^n) until memory is exhausted and your machine starts swapping. Around fib(35) on a 2GB Core2Duo.
 
===Iterative===
<langsyntaxhighlight lang="idl">function fib,n
psum = (csum = 1uL)
if n lt 3 then return,csum
Line 6,054 ⟶ 7,652:
endfor
return,nsum
end</langsyntaxhighlight>
 
Execution time O(n). Limited by size of uLong to fib(49)
 
===Analytic===
<langsyntaxhighlight lang="idl">function fib,n
q=1/( p=(1+sqrt(5))/2 )
return,round((p^n+q^n)/sqrt(5))
end</langsyntaxhighlight>
 
Execution time O(1), only limited by the range of LongInts to fib(48).
Line 6,069 ⟶ 7,667:
 
===Analytic===
<langsyntaxhighlight lang="idris">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</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight lang="idris">fibRecursive : Nat -> Nat
fibRecursive Z = Z
fibRecursive (S Z) = (S Z)
fibRecursive (S (S n)) = fibRecursive (S n) + fibRecursive n </langsyntaxhighlight>
===Iterative===
<langsyntaxhighlight lang="idris">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) </langsyntaxhighlight>
===Lazy===
<langsyntaxhighlight lang="idris">fibLazy : Lazy (List Nat)
fibLazy = 0 :: 1 :: zipWith (+) fibLazy (
case fibLazy of
(x::xs) => xs
[] => []) </langsyntaxhighlight>
 
=={{header|J}}==
The [[jhttps://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. Here is one:
 
<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:'''
<langsyntaxhighlight lang="j"> 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</langsyntaxhighlight>
 
(This implementation is doubly recursive except that results are cached across function calls.)
 
=={{header|Java}}==
===Iterative===
<langsyntaxhighlight lang="java">public static long itFibN(int n)
{
if (n < 2)
Line 6,119 ⟶ 7,719:
}
return ans;
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="java">
/**
* O(log(n))
Line 6,150 ⟶ 7,750:
return a + b;
}
</syntaxhighlight>
</lang>
 
===Recursive===
<langsyntaxhighlight lang="java">public static long recFibN(final int n)
{
return (n < 2) ? n : recFibN(n - 1) + recFibN(n - 2);
}</langsyntaxhighlight>
 
===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.
<langsyntaxhighlight lang="java">public class Fibonacci {
 
static final Map<Integer, Long> cache = new HashMap<>();
Line 6,177 ⟶ 7,777:
return cache.computeIfAbsent(n, k -> impl(k-1) + impl(k-2));
}
}</langsyntaxhighlight>
===Analytic===
This method works up to the 92<sup>nd</sup> Fibonacci number. After that, it goes out of range.
<langsyntaxhighlight lang="java">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));
}</langsyntaxhighlight>
===Tail-recursive===
<langsyntaxhighlight lang="java">public static long fibTailRec(final int n)
{
return fibInner(0, 1, n);
Line 6,195 ⟶ 7,795:
{
return n < 1 ? a : n == 1 ? b : fibInner(b, a + b, n - 1);
}</langsyntaxhighlight>
===Streams===
<langsyntaxhighlight lang="java5">
import java.util.function.LongUnaryOperator;
import java.util.stream.LongStream;
Line 6,216 ⟶ 7,816:
}
}
</syntaxhighlight>
</lang>
 
=={{header|JavaScript}}==
Line 6,222 ⟶ 7,822:
====Recursive====
Basic recursive function:
<langsyntaxhighlight lang="javascript">function fib(n) {
return n<2?n:fib(n-1)+fib(n-2);
}</langsyntaxhighlight>
Can be rewritten as:
<langsyntaxhighlight lang="javascript">function fib(n) {
if (n<2) { return n; } else { return fib(n-1)+fib(n-2); }
}</langsyntaxhighlight>
 
One possibility familiar to Scheme programmers is to define an internal function for iteration through anonymous tail recursion:
<langsyntaxhighlight lang="javascript">function fib(n) {
return function(n,a,b) {
return n>0 ? arguments.callee(n-1,b,a+b) : a;
}(n,0,1);
}</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight lang="javascript">function fib(n) {
var a = 0, b = 1, t;
while (n-- > 0) {
Line 6,247 ⟶ 7,847:
}
return a;
}</langsyntaxhighlight>
 
====Memoization====
Line 6,253 ⟶ 7,853:
With the keys of a dictionary,
 
<langsyntaxhighlight lang="javascript">var fib = (function(cache){
return cache = cache || {}, function(n){
if (cache[n]) return cache[n];
Line 6,260 ⟶ 7,860:
};
})();
</syntaxhighlight>
</lang>
 
with the indices of an array,
 
<langsyntaxhighlight lang="javascript">(function () {
'use strict';
 
Line 6,280 ⟶ 7,880:
return fib(32);
 
})();</langsyntaxhighlight>
 
 
Line 6,288 ⟶ 7,888:
 
====Y-Combinator====
<langsyntaxhighlight lang="javascript">function Y(dn) {
return (function(fn) {
return fn(fn);
Line 6,304 ⟶ 7,904:
return fn(n - 1) + fn(n - 2);
};
});</langsyntaxhighlight>
 
====Generators====
<langsyntaxhighlight lang="javascript">function* fibonacciGenerator() {
var prev = 0;
var curr = 1;
Line 6,316 ⟶ 7,916:
}
}
var fib = fibonacciGenerator();</langsyntaxhighlight>
 
===ES6===
Line 6,325 ⟶ 7,925:
we can use an accumulating fold.
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 6,359 ⟶ 7,959:
 
// --> 2178309
})();</langsyntaxhighlight>
 
Otherwise, a simple fold will suffice.
Line 6,365 ⟶ 7,965:
{{Trans|Haskell}} (Memoized fold example)
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 6,386 ⟶ 7,986:
 
// --> 2178309
})();</langsyntaxhighlight>
 
{{Out}}
Line 6,393 ⟶ 7,993:
=={{header|Joy}}==
===Recursive===
<langsyntaxhighlight lang="joy">DEFINE fib == [small] [] [pred dup pred] [+] binrec.</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight lang="joy">DEFINE fib == [1 0] dip [swap [+] unary] times popd.</langsyntaxhighlight>
 
=={{header|jq}}==
Line 6,405 ⟶ 8,005:
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">
<lang jq>
nth_fib(pow(2;20)) | tostring | [length, .[:10], .[-10:]]
</syntaxhighlight>
</lang>
yields
<pre>
Line 6,419 ⟶ 8,019:
 
===Recursive===
<langsyntaxhighlight lang="jq">def nth_fib_naive(n):
if (n < 2) then n
else nth_fib_naive(n - 1) + nth_fib_naive(n - 2)
end;</langsyntaxhighlight>
===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.
<langsyntaxhighlight lang="jq">def nth_fib(n):
# input: [f(i-2), f(i-1), countdown]
def fib: (.[0] + .[1]) as $sum
Line 6,433 ⟶ 8,033:
| fib end;
[-1, 1, n] | fib;
</syntaxhighlight>
</lang>
 
Example:<langsyntaxhighlight lang="jq">
(range(0;5), 50) | [., nth_fib(.)]
</syntaxhighlight>
</lang>
yields: <langsyntaxhighlight lang="jq">[0,0]
[1,1]
[2,1]
[3,2]
[4,3]
[50,12586269025]</langsyntaxhighlight>
 
===Binet's Formula===
<langsyntaxhighlight lang="jq">def fib_binet(n):
(5|sqrt) as $rt
| ((1 + $rt)/2) as $phi
Line 6,452 ⟶ 8,052:
| (if 0 == (n % 2) then 1 else -1 end) as $sign
| ( ($phin - ($sign / $phin) ) / $rt ) + .5
| floor;</langsyntaxhighlight>
 
===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)".<langsyntaxhighlight lang="jq"># Generator
def fibonacci(n):
# input: [f(i-2), f(i-1), countdown]
Line 6,462 ⟶ 8,062:
else $sum, ([ .[1], $sum, .[2] - 1 ] | fib)
end;
[-1, 1, n] | fib;</langsyntaxhighlight>
 
=={{header|Julia}}==
===Recursive===
<langsyntaxhighlight Julialang="julia">fib(n) = n < 2 ? n : fib(n-1) + fib(n-2)</langsyntaxhighlight>
===Iterative===
<langsyntaxhighlight Julialang="julia">function fib(n)
x,y = (0,1)
for i = 1:n x,y = (y, x+y) end
x
end</langsyntaxhighlight>
===Matrix form===
<langsyntaxhighlight Julialang="julia">fib(n) = ([1 1 ; 1 0]^n)[1,2]</langsyntaxhighlight>
 
=={{header|K}}==
{{works with|Kona}}
 
===Recursive===
<langsyntaxhighlight Klang="k">{:[x<3;1;_f[x-1]+_f[x-2]]}</langsyntaxhighlight>
 
===Recursive with memoization===
Using a (global) dictionary c.
 
<langsyntaxhighlight Klang="k">{c::.();{v:c[a:`$$x];:[x<3;1;:[_n~v;c[a]:_f[x-1]+_f[x-2];v]]}x}</langsyntaxhighlight>
 
===Analytic===
<langsyntaxhighlight Klang="k">phi:(1+_sqrt(5))%2
{_((phi^x)-((1-phi)^x))%_sqrt[5]}</langsyntaxhighlight>
 
===Sequence to n===
{{works with|Kona}} {{works with|ngn/k}}
<lang K>{(x(|+\)\1 1)[;1]}</lang>
<syntaxhighlight lang K="k">{(x{x,(|+/-2#x}/!2\)\1 1)[;1]}</langsyntaxhighlight>
<syntaxhighlight lang="k">{x{x,+/-2#x}/!2}</syntaxhighlight>
 
=={{header|Kabap}}==
 
===Sequence to n===
<syntaxhighlight lang="kabap">
<lang Kabap>
// Calculate the $n'th Fibonacci number
 
Line 6,533 ⟶ 8,135:
// Return the sequence
return = "Fibonacci number " << $i << " is " << $a << " (" << $sequence << ")";
</syntaxhighlight>
</lang>
 
=={{header|Klingphix}}==
<syntaxhighlight lang="text">:Fibonacci
dup 0 less
( ["Invalid argument"]
Line 6,546 ⟶ 8,148:
 
msec print nl
"bertlham " input</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="kotlin">enum class Fibonacci {
ITERATIVE {
override fun get(n: Int): Long = if (n < 2) {
Line 6,584 ⟶ 8,186:
println()
}
}</langsyntaxhighlight>
{{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
Line 6,592 ⟶ 8,194:
 
=={{header|L++}}==
<langsyntaxhighlight lang="lisp">(defn int fib (int n) (return (? (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))))
(main (prn (fib 30)))</langsyntaxhighlight>
 
=={{header|LabVIEW}}==
{{VI solution|LabVIEW_Fibonacci_sequence.png}}
 
=={{header|lambdatalkLambdatalk}}==
 
<langsyntaxhighlight lang="scheme">
1) basic version
{def fib1
Line 6,684 ⟶ 8,286:
{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}}==
<langsyntaxhighlight 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 ;
Line 6,693 ⟶ 8,329:
 
: fib dup 1 > if dup 1- fib swap 2 - fib + then ;
: fib dup 1 > if "1- fib" "2 - fib" bi + then ;</langsyntaxhighlight>
 
=={{header|langur}}==
<langsyntaxhighlight lang="langur">val .fibonacci = ffn(.x) { if(.x < 2: .x ; self(.x - 1) + self(.x - 2)) }
 
writeln map .fibonacci, series 2..20</langsyntaxhighlight>
 
{{out}}
Line 6,704 ⟶ 8,340:
 
=={{header|Lasso}}==
<syntaxhighlight lang="lasso">
<lang Lasso>
define fibonacci(n::integer) => {
 
Line 6,728 ⟶ 8,364:
fibonacci(2) //->output 1
fibonacci(3) //->output 2
</syntaxhighlight>
</lang>
 
=={{header|Latitude}}==
 
===Recursive===
<langsyntaxhighlight lang="latitude">fibo := {
takes '[n].
if { n <= 1. } then {
Line 6,740 ⟶ 8,376:
fibo (n - 1) + fibo (n - 2).
}.
}.</langsyntaxhighlight>
 
===Memoization===
<langsyntaxhighlight lang="latitude">fibo := {
takes '[n].
cache := here cache.
Line 6,758 ⟶ 8,394:
;; Attach the cache to the method object itself.
#'self cache := Object clone.
}.</langsyntaxhighlight>
 
 
Line 6,765 ⟶ 8,401:
It runs on Lean 3.4.2:
 
<syntaxhighlight lang="lean">
<lang Lean>
-- Our first implementation is the usual recursive definition:
def fib1 : ℕ → ℕ
Line 6,784 ⟶ 8,420:
-- Use #eval to check computations:
#eval fib1 20
#eval fib2 20</langsyntaxhighlight>
 
 
It runs on Lean 4:
 
<syntaxhighlight lang="lean">
<lang Lean>
-- Naive version
def fib1 (n : Nat) : Nat :=
Line 6,809 ⟶ 8,445:
#eval fib1 20
#eval fib2 20
</syntaxhighlight>
</lang>
 
=={{header|LFE}}==
Line 6,815 ⟶ 8,451:
===Recursive===
 
<langsyntaxhighlight lang="lisp">
(defun fib
((0) 0)
Line 6,822 ⟶ 8,458:
(+ (fib (- n 1))
(fib (- n 2)))))
</syntaxhighlight>
</lang>
 
===Iterative===
 
<langsyntaxhighlight lang="lisp">
(defun fib
((n) (when (>= n 0))
Line 6,837 ⟶ 8,473:
(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}}==
 
===Recursive===
<syntaxhighlight lang="lingo">on fib (n)
 
<lang lingo>on fib (n)
if n<2 then return n
return fib(n-1)+fib(n-2)
end</langsyntaxhighlight>
 
===Iterative===
<syntaxhighlight lang="lingo">on fib (n)
 
<lang lingo>on fib (n)
if n<2 then return n
fibPrev = 0
Line 6,979 ⟶ 8,494:
end repeat
return fib
end</langsyntaxhighlight>
 
===Analytic===
<syntaxhighlight lang="lingo">on fib (n)
 
<lang lingo>on fib (n)
sqrt5 = sqrt(5.0)
p = (1+sqrt5)/2
q = 1 - p
return integer((power(p,n)-power(q,n))/sqrt5)
end</langsyntaxhighlight>
 
=={{header|Lisaac}}==
<langsyntaxhighlight Lisaaclang="lisaac">- fib(n : UINTEGER_32) : UINTEGER_64 <- (
+ result : UINTEGER_64;
(n < 2).if {
Line 6,999 ⟶ 8,513:
};
result
);</langsyntaxhighlight>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">-- Iterative, translation of the basic version.
function fibi n
put 0 into aa
Line 7,021 ⟶ 8,535:
return fibr(n-1) + fibr(n-2)
end if
end fibr</langsyntaxhighlight>
 
=={{header|LLVM}}==
<langsyntaxhighlight 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.
Line 7,093 ⟶ 8,607:
exit:
ret i32 0 ;-- return EXIT_SUCCESS
}</langsyntaxhighlight>
{{out}}
<pre>0
Line 7,110 ⟶ 8,624:
 
=={{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}}==
<syntaxhighlight lang="lolcode">
<lang LOLCODE>
HAI 1.2
HOW DUZ I fibonacci YR N
Line 7,133 ⟶ 8,662:
IF U SAY SO
KTHXBYE
</syntaxhighlight>
</lang>
 
=={{header|LSL}}==
Rez a box on the ground, and add the following as a New Script.
<langsyntaxhighlight LSLlang="lsl">integer Fibonacci(integer n) {
if(n<2) {
return n;
Line 7,151 ⟶ 8,680:
}
}
}</langsyntaxhighlight>
Output:
<pre>
Line 7,193 ⟶ 8,722:
=={{header|Lua}}==
===Recursive===
<langsyntaxhighlight 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>
</lang>
 
===Pedantic Recursive===
<langsyntaxhighlight lang="lua">
--more pedantic version, returns 0 for non-integer n
function pfibs(n)
Line 7,210 ⟶ 8,739:
end
end
</syntaxhighlight>
</lang>
 
===Tail Recursive===
<langsyntaxhighlight 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>
</lang>
 
===Table Recursive===
<langsyntaxhighlight 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>
</lang>
 
===Table Recursive 2===
<langsyntaxhighlight 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}).
Line 7,234 ⟶ 8,763:
end
})
</syntaxhighlight>
</lang>
 
===Iterative===
<langsyntaxhighlight lang="lua">
function ifibs(n)
local p0,p1=0,1
Line 7,243 ⟶ 8,772:
return p0
end
</syntaxhighlight>
</lang>
 
=={{header|Luck}}==
<langsyntaxhighlight lang="luck">function fib(x: int): int = (
let cache = {} in
let fibc x = if x<=1 then x else (
Line 7,254 ⟶ 8,783:
) in fibc(x)
);;
for x in range(10) do print(fib(x))</langsyntaxhighlight>
 
=={{header|Lush}}==
<langsyntaxhighlight lang="lush">(de fib-rec (n)
(if (< n 2)
n
(+ (fib-rec (- n 2)) (fib-rec (- n 1)))))</langsyntaxhighlight>
 
=={{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.
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Inventory K=0:=0,1:=1
fib=Lambda K (x as decimal)-> {
Line 7,277 ⟶ 8,806:
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.
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
 
Class BigNum {
Line 7,362 ⟶ 8,891:
 
 
</syntaxhighlight>
</lang>
 
=={{header|M4}}==
<langsyntaxhighlight lang="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')</langsyntaxhighlight>
 
=={{header|MAD}}==
 
<langsyntaxhighlight MADlang="mad"> NORMAL MODE IS INTEGER
INTERNAL FUNCTION(N)
Line 7,388 ⟶ 8,917:
SHOW PRINT FORMAT FNUM, I, FIB.(I)
VECTOR VALUES FNUM = $4HFIB(,I2,4H) = ,I4*$
END OF PROGRAM </langsyntaxhighlight>
 
{{out}}
Line 7,415 ⟶ 8,944:
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">
> f := n -> ifelse(n<3,1,f(n-1)+f(n-2));
> f(2);
Line 7,421 ⟶ 8,950:
> f(3);
2
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
The Wolfram Language already has a built-in function <tt>Fibonacci</tt>, but a simple recursive implementation would be
 
<langsyntaxhighlight lang="mathematica">fib[0] = 0
fib[1] = 1
fib[n_Integer] := fib[n - 1] + fib[n - 2]</langsyntaxhighlight>
 
An optimization is to cache the values already calculated:
 
<langsyntaxhighlight lang="mathematica">fib[0] = 0
fib[1] = 1
fib[n_Integer] := fib[n] = fib[n - 1] + fib[n - 2]</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="mathematica">fibi[prvprv_Integer, prv_Integer, rm_Integer] :=
If[rm < 1, prvprv, fibi[prv, prvprv + prv, rm - 1]]
fib[n_Integer] := fibi[0, 1, n]</langsyntaxhighlight>
 
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):
 
<langsyntaxhighlight lang="mathematica">fib[n_Integer] := Block[{tmp, prvprv = 0, prv = 1},
For[i = 0, i < n, i++, tmp = prv; prv += prvprv; prvprv = tmp];
Return[prvprv]]</langsyntaxhighlight>
 
If one wanted a list of Fibonacci numbers, the following is quite efficient:
 
<langsyntaxhighlight lang="mathematica">fibi[{prvprv_Integer, prv_Integer}] := {prv, prvprv + prv}
fibList[n_Integer] := Map[Take[#, 1] &, NestList[fibi, {0, 1}, n]] // Flatten</langsyntaxhighlight>
 
Output from the last with "fibList[100]":
 
<langsyntaxhighlight 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, \
196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, \
Line 7,475 ⟶ 9,004:
19740274219868223167, 31940434634990099905, 51680708854858323072, \
83621143489848422977, 135301852344706746049, 218922995834555169026, \
354224848179261915075}</langsyntaxhighlight>
 
The Wolfram Language can also solve recurrence equations using the built-in function <tt>RSolve</tt>
 
<langsyntaxhighlight lang="mathematica">fib[n] /. RSolve[{fib[n] == fib[n - 1] + fib[n - 2], fib[0] == 0,
fib[1] == 1}, fib[n], n][[1]]</langsyntaxhighlight>
 
which evaluates to the built-in function <tt>Fibonacci[n]</tt>
Line 7,486 ⟶ 9,015:
This function can also be expressed as
 
<langsyntaxhighlight lang="mathematica">Fibonacci[n] // FunctionExpand // FullSimplify</langsyntaxhighlight>
 
which evaluates to
 
<langsyntaxhighlight lang="mathematica">(2^-n ((1 + Sqrt[5])^n - (-1 + Sqrt[5])^n Cos[n π]))/Sqrt[5]</langsyntaxhighlight>
 
and is defined for all real or complex values of n.
Line 7,499 ⟶ 9,028:
{{trans|Julia}}
 
<langsyntaxhighlight MATLABlang="matlab">function f = fib(n)
f = [1 1 ; 1 0]^(n-1);
f = f(1,1);
end</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight MATLABlang="matlab">function F = fibonacci(n)
Fn = [1 0]; %Fn(1) is F_{n-2}, Fn(2) is F_{n-1}
Line 7,522 ⟶ 9,051:
end
 
end</langsyntaxhighlight>
 
===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.
 
<langsyntaxhighlight MATLABlang="matlab">function number = fibonacci2(n)
if n == 1
Line 7,539 ⟶ 9,068:
end
 
end</langsyntaxhighlight>
 
===Tartaglia/Pascal Triangle Method===
<syntaxhighlight lang="matlab">
<lang Matlab>
function number = fibonacci(n)
%construct the Tartaglia/Pascal Triangle
Line 7,555 ⟶ 9,084:
number=trace(rot90(pt));
end
</syntaxhighlight>
</lang>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">/* fib(n) is built-in; here is an implementation */
fib2(n) := (matrix([0, 1], [1, 1])^^n)[1, 2]$
 
Line 7,565 ⟶ 9,094:
 
fib2(-10);
-55</langsyntaxhighlight>
 
=={{header|MAXScript}}==
===Iterative===
<langsyntaxhighlight lang="maxscript">fn fibIter n =
(
if n < 2 then
Line 7,587 ⟶ 9,116:
fib
)
)</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight lang="maxscript">fn fibRec n =
(
if n < 2 then
Line 7,599 ⟶ 9,128:
fibRec (n - 1) + fibRec (n - 2)
)
)</langsyntaxhighlight>
 
=={{header|Mercury}}==
Line 7,607 ⟶ 9,136:
 
===fib.m===
<langsyntaxhighlight lang="mercury">
% The following code is derived from the Mercury Tutorial by Ralph Becket.
% http://www.mercury.csse.unimelb.edu.au/information/papers/book.pdf
Line 7,637 ⟶ 9,166:
write_int(fib(40), !IO),
write_string("\n", !IO).
</syntaxhighlight>
</lang>
 
=== Iterative algorithm ===
Line 7,643 ⟶ 9,172:
The much faster iterative algorithm can be written as:
 
<langsyntaxhighlight lang="mercury">
:- pred fib_acc(int::in, int::in, int::in, int::in, int::out) is det.
 
Line 7,659 ⟶ 9,188:
Res = Prev2 + Prev1
).
</syntaxhighlight>
</lang>
 
This predicate can be called as <langsyntaxhighlight lang="mercury">fib_acc(1, 40, 1, 1, Result)</langsyntaxhighlight>
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 7,668 ⟶ 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:
 
<langsyntaxhighlight lang="mercury">
:- pragma memo(fib/2).
:- pred fib(int::in, int::out) is det.
Line 7,675 ⟶ 9,204:
then X = 1
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.
Line 7,682 ⟶ 9,211:
 
=={{header|Metafont}}==
<langsyntaxhighlight lang="metafont">vardef fibo(expr n) =
if n=0: 0
elseif n=1: 1
Line 7,691 ⟶ 9,220:
 
for i=0 upto 10: show fibo(i); endfor
end</langsyntaxhighlight>
 
=={{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|min}}==
{{works with|min|0.1937.30}}
<langsyntaxhighlight lang="min">(
(2 <)
((0pred (1 0 (dup rollupover + swap)) dip pred times nippop)
unless
) :^fib</langsyntaxhighlight>
 
=={{header|MiniScript}}==
An efficient solution (for n >= 0):
<langsyntaxhighlight MiniScriptlang="miniscript">fibonacci = function(n)
if n < 2 then return n
n1 = 0
Line 7,751 ⟶ 9,245:
end function
 
print fibonacci(6)</langsyntaxhighlight>
 
And for comparison, a recursive solution (also for n >= 0):
<langsyntaxhighlight MiniScriptlang="miniscript">rfib = function(n)
if n < 1 then return 0
if n == 1 then return 1
Line 7,760 ⟶ 9,254:
end function
 
print rfib(6)</langsyntaxhighlight>
=={{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}}==
 
This is the iterative approach to the Fibonacci sequence.
<syntaxhighlight lang="mips">
<lang MIPS>
.text
main: li $v0, 5 # read integer from input. The read integer will be stroed in $v0
Line 7,809 ⟶ 9,319:
li $v0, 10
syscall
</syntaxhighlight>
</lang>
 
=={{header|Mirah}}==
<langsyntaxhighlight lang="mirah">def fibonacci(n:int)
return n if n < 2
fibPrev = 1
Line 7,831 ⟶ 9,341:
puts fibonacci 6
puts fibonacci 7
</syntaxhighlight>
</lang>
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">П0 1 lg Вx <-> + L0 03 С/П БП
03</langsyntaxhighlight>
 
Instruction: ''n'' В/О С/П, where ''n'' is serial number of the number of Fibonacci sequence; С/П for the following numbers.
Line 7,843 ⟶ 9,353:
====Tail Recursion====
This version is tail recursive.
<langsyntaxhighlight lang="sml">fun fib n =
let
fun fib' (0,a,b) = a
Line 7,849 ⟶ 9,359:
in
fib' (n,0,1)
end</langsyntaxhighlight>
 
====Recursion====
<langsyntaxhighlight lang="sml">fun fib n = if n < 2 then n else fib (n - 1) + fib (n - 2)</langsyntaxhighlight>
 
==={{header|MLite}}===
====Recursion====
Tail recursive.
<langsyntaxhighlight lang="ocaml">fun fib
(0, x1, x2) = x2
| (n, x1, x2) = fib (n-1, x2, x1+x2)
| n = fib (n, 0, 1)</langsyntaxhighlight>
 
=={{header|ML/I}}==
<langsyntaxhighlight MLlang="ml/Ii">MCSKIP "WITH" NL
"" Fibonacci - recursive
MCSKIP MT,<>
Line 7,877 ⟶ 9,387:
fib(3) is FIB(3)
fib(4) is FIB(4)
fib(5) is FIB(5)</langsyntaxhighlight>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE Fibonacci;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 7,916 ⟶ 9,426:
 
ReadChar
END Fibonacci.</langsyntaxhighlight>
 
=={{header|Modula-3}}==
===Recursive===
<langsyntaxhighlight lang="modula3">PROCEDURE Fib(n: INTEGER): INTEGER =
BEGIN
IF n < 2 THEN
Line 7,927 ⟶ 9,437:
RETURN Fib(n-1) + Fib(n-2);
END;
END Fib;</langsyntaxhighlight>
 
=== Iterative (with negatives) ===
 
<langsyntaxhighlight lang="modula3">PROCEDURE IterFib(n: INTEGER): INTEGER =
 
VAR
Line 7,966 ⟶ 9,476:
RETURN curr;
 
END IterFib;</langsyntaxhighlight>
 
=={{header|Monicelli}}==
Recursive version. It includes a main that reads a number N from standard input and prints the Nth Fibonacci number.
<langsyntaxhighlight lang="monicelli">
# Main
Lei ha clacsonato
Line 7,983 ⟶ 9,493:
Necchi come se fosse brematurata la supercazzola bonaccia con antani meno 2 o scherziamo? vaffanzum
unchiamo più duechiamo! e velocità di esecuzione
</syntaxhighlight>
</lang>
 
=={{header|MontiLang}}==
Reads number from standard input and prints to that number in the fibonacci sequence
<langsyntaxhighlight MontiLanglang="montilang">0 VAR a .
1 VAR b .
INPUT TOINT
Line 7,995 ⟶ 9,505:
b VAR a .
c VAR b .
ENDFOR</langsyntaxhighlight>
 
Forth-style solution
 
<langsyntaxhighlight MontiLanglang="montilang">def over
swap dup rot swap
enddef
Line 8,010 ⟶ 9,520:
. print
input
clear</langsyntaxhighlight>
 
Simpler
 
<langsyntaxhighlight MontiLanglang="montilang">|Enter a number to obtain Fibonacci sequence: | input nip 1 - var count .
0 1
FOR count
Line 8,021 ⟶ 9,531:
print
input /# wait until press ENTER #/
clear /# empties the stack #/</langsyntaxhighlight>
 
=={{header|MUMPS}}==
===Iterative===
<langsyntaxhighlight MUMPSlang="mumps">FIBOITER(N)
;Iterative version to get the Nth Fibonacci number
;N must be a positive integer
Line 8,035 ⟶ 9,545:
QUIT:N<2 F(N)
FOR I=2:1:N SET F(I)=F(I-1)+F(I-2)
QUIT F(N)</langsyntaxhighlight>
 
<pre>
Line 8,044 ⟶ 9,554:
=={{header|Nanoquery}}==
===Iterative===
<langsyntaxhighlight lang="nanoquery">def fibIter(n)
if (n < 2)
return n
Line 8,058 ⟶ 9,568:
return fib
end</langsyntaxhighlight>
 
=={{header|Nemerle}}==
===Recursive===
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
 
Line 8,079 ⟶ 9,589:
WriteLine("{0}: {1}", n, Fibonacci(n));
}
}</langsyntaxhighlight>
===Tail Recursive===
<langsyntaxhighlight Nemerlelang="nemerle">Fibonacci(x : long, current : long, next : long) : long
{
match(x)
Line 8,093 ⟶ 9,603:
{
Fibonacci(x, 0, 1)
}</langsyntaxhighlight>
 
=={{header|NESL}}==
===Recursive===
<langsyntaxhighlight lang="nesl">function fib(n) = if n < 2 then n else fib(n - 2) + fib(n - 1);</langsyntaxhighlight>
 
=={{header|NetRexx}}==
{{trans|REXX}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
 
options replace format comments java crossref savelog symbols
Line 8,138 ⟶ 9,648:
if n > 0 | na // 2 == 1 then return s /*if positive or odd negative... */
else return -s /*return a negative Fib number. */
</syntaxhighlight>
</lang>
 
=={{header|NewLISP}}==
===Iterative===
<langsyntaxhighlight newLISPlang="newlisp">(define (fibonacci n)
(let (L '(0 1))
(dotimes (i n)
(setq L (list (L 1) (apply + L))))
(L 1)) )
</syntaxhighlight>
</lang>
 
===Recursive===
<langsyntaxhighlight newLISPlang="newlisp">(define (fibonacci n)
(if (< n 2) 1
(+ (fibonacci (- n 1))
(fibonacci (- n 2)))))
</syntaxhighlight>
</lang>
 
===Matrix multiplication===
<langsyntaxhighlight newLISPlang="newlisp">(define (fibonacci n)
(letn (f '((0 1) (1 1)) fib f)
(dotimes (i n)
Line 8,163 ⟶ 9,673:
(fib 0 1)) )
 
(print(fibonacci 10)) ;;89</langsyntaxhighlight>
 
===With a stack ===
<syntaxhighlight lang="newlisp">
<lang newLISP>
;;; Global variable (bigints); can be isolated in a namespace if need be
(setq stack '(0L 1L))
Line 8,182 ⟶ 9,692:
(println (length (fib 50000)))
;;; outputs 10450 (digits)
</syntaxhighlight>
</lang>
 
=={{header|NGS}}==
===Iterative===
{{trans|Python}}
<langsyntaxhighlight NGSlang="ngs">F fib(n:Int) {
n < 2 returns n
local a = 1, b = 1
Line 8,197 ⟶ 9,707:
}
b
}</langsyntaxhighlight>
 
=={{header|Nial}}==
Line 8,206 ⟶ 9,716:
single iteration with n=1,000,000 takes it about 15s.
 
<langsyntaxhighlight lang="nial">fibi is op n {
if n<2 then
n
Line 8,217 ⟶ 9,727:
endfor;
x2
endif};</langsyntaxhighlight>
 
Iterative using fold. Slightly faster, <1.6s:
 
<langsyntaxhighlight lang="nial">fibf is op n {1 pick ((n- 1) fold [1 pick, +] 0 1)};</langsyntaxhighlight>
 
Tacit verion of above. Slightly faster still, <1.4s:
 
<langsyntaxhighlight lang="nial">fibf2 is 1 pick fold [1 pick, +] reverse (0 1 hitch) (-1+);</langsyntaxhighlight>
 
===Recursive===
Line 8,231 ⟶ 9,741:
(Similar to time for recursive python version with n=37.)
 
<langsyntaxhighlight lang="nial">fibr is op n {fork [2>, +, + [fibr (-1 +), fibr (-2 +)]] n};</langsyntaxhighlight>
 
...or tacit version. More than twice as fast (?) but still slow:
 
<langsyntaxhighlight lang="nial">fibr2 is fork [2>, +, + [fibr2 (-1 +), fibr2 (-2 +)]];</langsyntaxhighlight>
 
===Matrix===
Line 8,242 ⟶ 9,752:
Note that n>92 produces negative result.
 
<langsyntaxhighlight lang="nial">fibm is op n {floor (0 1 pick (reduce ip (n reshape [2 2 reshape 1 1 1 0])))};</langsyntaxhighlight>
 
Could it look a little more like J?
(Maybe 5% slower than above.)
 
<langsyntaxhighlight 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](~$)));</langsyntaxhighlight>
 
Alternate, not involving replicating matrix n times, but maybe 50% slower
than the fastest matrix version above - similar speed to iterative:
 
<langsyntaxhighlight lang="nial">fibm3 is op n {a:=2 2$1 1 1 0; _(0 1 pick ((n- 1) fold (a ip) a))};</langsyntaxhighlight>
 
=={{header|Nim}}==
===Analytic===
<langsyntaxhighlight lang="nim">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))</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight lang="nim">proc Fibonacci(n: int): int =
var
first = 0
Line 8,276 ⟶ 9,786:
second += first
 
result = first</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="nim">proc Fibonacci(n: int): int64 =
if n <= 2:
result = 1
else:
result = Fibonacci(n - 1) + Fibonacci(n - 2)</langsyntaxhighlight>
 
===Tail-recursive===
<langsyntaxhighlight lang="nim">proc Fibonacci(n: int, current: int64, next: int64): int64 =
if n == 0:
result = current
Line 8,292 ⟶ 9,802:
result = Fibonacci(n - 1, next, current + next)
proc Fibonacci(n: int): int64 =
result = Fibonacci(n, 0, 1)</langsyntaxhighlight>
 
===Continuations===
<langsyntaxhighlight lang="nim">iterator fib: int {.closure.} =
var a = 0
var b = 1
Line 8,305 ⟶ 9,815:
var f = fib
for i in 0.. <10:
echo f()</langsyntaxhighlight>
=={{header|Nix}}==
<langsyntaxhighlight lang="nix">fibonacci = n:
if n <= 1 then n else (fibonacci (n - 1) + fibonacci (n - 2));</langsyntaxhighlight>
 
=={{header|Oberon-2}}==
{{Works with|oo2c Version 2}}
<langsyntaxhighlight lang="oberon2">
MODULE Fibonacci;
IMPORT
Line 8,373 ⟶ 9,883:
GenR(20);
END Fibonacci.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 8,388 ⟶ 9,898:
=={{header|Objeck}}==
===Recursive===
<langsyntaxhighlight lang="objeck">bundle Default {
class Fib {
function : Main(args : String[]), Nil {
Line 8,404 ⟶ 9,914:
}
}
}</langsyntaxhighlight>
 
=={{header|Objective-C}}==
===Recursive===
<langsyntaxhighlight lang="objc">-(long)fibonacci:(int)position
{
long result = 0;
Line 8,417 ⟶ 9,927:
}
return result;
}</langsyntaxhighlight>
===Iterative===
<langsyntaxhighlight lang="objc">+(long)fibonacci:(int)index {
long beforeLast = 0, last = 1;
while (index > 0) {
Line 8,427 ⟶ 9,937:
}
return last;
}</langsyntaxhighlight>
 
=={{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===
<langsyntaxhighlight lang="ocaml">let fib_iter n =
if n < 2 then
n
Line 8,441 ⟶ 9,958:
fib_prev := temp
done;
!fib</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="ocaml">let rec fib_rec n =
if n < 2 then
n
else
fib_rec (n - 1) + fib_rec (n - 2)
Line 8,455 ⟶ 9,972:
| n -> if n > 0 then fib (n-1) + fib (n-2)
else fib (n+2) - fib (n+1)
</syntaxhighlight>
</lang>
 
===Arbitrary Precision===
Using OCaml's [http://caml.inria.fr/pub/docs/manual-ocaml/libref/Num.html Num] module.
 
<langsyntaxhighlight lang="ocaml">open Num
 
let fib =
Line 8,479 ⟶ 9,996:
let n = int_of_string Sys.argv.(1) in
print_endline (string_of_num (fib n))
</syntaxhighlight>
</lang>
 
compile with:
Line 8,497 ⟶ 10,014:
=== 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)).
<langsyntaxhighlight lang="ocaml">open Num
 
let mul (a,b,c) (d,e,f) = let bxe = b*/e in
Line 8,512 ⟶ 10,029:
string_of_num y
;;
Printf.printf "fib %d = %s\n" 300 (fib 300)</langsyntaxhighlight>
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}}==
===Recursive===
<langsyntaxhighlight lang="octave">% recursive
function fibo = recfibo(n)
if ( n < 2 )
Line 8,524 ⟶ 10,072:
fibo = recfibo(n-1) + recfibo(n-2);
endif
endfunction</langsyntaxhighlight>
 
'''Testing'''
<langsyntaxhighlight lang="octave">% testing
for i = 0 : 20
printf("%d %d\n", i, recfibo(i));
endfor</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight lang="octave">% iterative
function fibo = iterfibo(n)
if ( n < 2 )
Line 8,548 ⟶ 10,096:
fibo = f(2);
endif
endfunction</langsyntaxhighlight>
 
'''Testing'''
<langsyntaxhighlight lang="octave">% testing
for i = 0 : 20
printf("%d %d\n", i, iterfibo(i));
endfor</langsyntaxhighlight>
 
===Analytic===
<langsyntaxhighlight lang="octave">function retval = fibanalytic(n)
retval = round(((5 .^ 0.5 + 1) / 2) .^ n / 5 .^ 0.5);
endfunction</langsyntaxhighlight>
 
===Tail Recursive===
<langsyntaxhighlight lang="octave">function retval = fibtailrecursive(n, prevfib = 0, fib = 1)
if (n == 0)
retval = prevfib;
Line 8,568 ⟶ 10,116:
retval = fibtailrecursive(n - 1, fib, prevfib + fib);
endif
endfunction</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight Oforthlang="oforth">: fib 0 1 rot #[ tuck + ] times drop ;</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="opl">FIBON:
REM Fibonacci sequence is generated to the Organiser II floating point variable limit.
REM CLEAR/ON key quits.
Line 8,589 ⟶ 10,272:
B=C
PRINT A,
UNTIL GET=1</langsyntaxhighlight>
 
=={{header|Order}}==
===Recursive===
<langsyntaxhighlight lang="c">#include <order/interpreter.h>
 
#define ORDER_PP_DEF_8fib_rec \
Line 8,602 ⟶ 10,285:
8fib_rec(8sub(8N, 2))))))
 
ORDER_PP(8fib_rec(10))</langsyntaxhighlight>
 
Tail recursive version (example supplied with language):
<langsyntaxhighlight lang="c">#include <order/interpreter.h>
#define ORDER_PP_DEF_8fib \
Line 8,617 ⟶ 10,300:
8fib_iter(8dec(8N), 8J, 8add(8I, 8J)))))
ORDER_PP(8to_lit(8fib(8nat(5,0,0))))</langsyntaxhighlight>
 
===Memoization===
<langsyntaxhighlight lang="c">#include <order/interpreter.h>
 
#define ORDER_PP_DEF_8fib_memo \
Line 8,644 ⟶ 10,327:
8print(8to_lit(8fib_memo(8N)) (,) 8space)),
1, 21)
)</langsyntaxhighlight>
 
=={{header|Oz}}==
Line 8,650 ⟶ 10,333:
===Iterative===
Using mutable references (cells).
<langsyntaxhighlight lang="oz">fun{FibI N}
Temp = {NewCell 0}
A = {NewCell 0}
Line 8,661 ⟶ 10,344:
end
@A
end</langsyntaxhighlight>
 
===Recursive===
Inefficient (blows up the stack).
<langsyntaxhighlight lang="oz">fun{FibR N}
if N < 2 then N
else {FibR N-1} + {FibR N-2}
end
end</langsyntaxhighlight>
 
===Tail-recursive===
Using accumulators.
<langsyntaxhighlight lang="oz">fun{Fib N}
fun{Loop N A B}
if N == 0 then
Line 8,683 ⟶ 10,366:
in
{Loop N 1 0}
end</langsyntaxhighlight>
 
===Lazy-recursive===
<langsyntaxhighlight lang="oz">declare
fun lazy {FiboSeq}
{LazyMap
Line 8,705 ⟶ 10,388:
end
in
{Show {List.take {FiboSeq} 8}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
===Built-in===
<syntaxhighlight lang ="parigp">fibonoccifibonacci(n)</langsyntaxhighlight>
 
===Matrix===
<langsyntaxhighlight lang="parigp">fib(n)=([1,1;1,0]^n)[1,2]</langsyntaxhighlight>
 
===Analytic===
This uses the Binet form.
<langsyntaxhighlight lang="parigp">fib(n)=my(phi=(1+sqrt(5))/2);round((phi^n-phi^-n)/sqrt(5))</langsyntaxhighlight>
The second term can be dropped since the error is always small enough to be subsumed by the rounding.
<langsyntaxhighlight lang="parigp">fib(n)=round(((1+sqrt(5))/2)^n/sqrt(5))</langsyntaxhighlight>
 
===Algebraic===
Line 8,725 ⟶ 10,408:
and hence <code>real(quadgen(5)^n)</code> would give the (n-1)-th Fibonacci number.
 
<langsyntaxhighlight lang="parigp">fib(n)=imag(quadgen(5)^n)</langsyntaxhighlight>
 
A more direct translation (note that <math>\sqrt5=2\phi-1</math>) would be
<langsyntaxhighlight lang="parigp">fib(n)=my(phi=quadgen(5));(phi^n-(-1/phi)^n)/(2*phi-1)</langsyntaxhighlight>
 
===Combinatorial===
This uses the generating function. It can be trivially adapted to give the first n Fibonacci numbers.
<langsyntaxhighlight lang="parigp">fib(n)=polcoeff(x/(1-x-x^2)+O(x^(n+1)),n)</langsyntaxhighlight>
 
===Binary powering===
<langsyntaxhighlight lang="parigp">fib(n)={
if(n<=0,
if(n,(-1)^(n+1)*fib(n),0)
Line 8,752 ⟶ 10,435:
if(n,[v[1]^2+2,v[1]*v[2]+1],[v[1]^2-2,v[1]*v[2]-1])
)
};</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="parigp">fib(n)={
if(n<2,
n
Line 8,761 ⟶ 10,444:
fib(n-1)+fib(n)
)
};</langsyntaxhighlight>
 
===Anonymous recursion===
{{works with|PARI/GP|2.8.0+}}
This uses <code>self()</code> which gives a self-reference.
<langsyntaxhighlight lang="parigp">fib(n)={
if(n<2,
n
Line 8,773 ⟶ 10,456:
s(n-2)+s(n-1)
)
};</langsyntaxhighlight>
 
It can be used without being named:
<langsyntaxhighlight lang="parigp">apply(n->if(n<2,n,my(s=self());s(n-2)+s(n-1)), [1..10])</langsyntaxhighlight>
gives
{{out}}
Line 8,782 ⟶ 10,465:
 
===Memoization===
<langsyntaxhighlight lang="parigp">F=[];
fib(n)={
if(n>#F,
Line 8,794 ⟶ 10,477:
)
);
}</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight lang="parigp">fib(n)={
if(n<0,return((-1)^(n+1)*fib(n)));
my(a=0,b=1,t);
Line 8,807 ⟶ 10,490:
);
a
};</langsyntaxhighlight>
 
===Chebyshev===
This solution uses Chebyshev polynomials of the second kind (Chyebyshev U-polynomials).
<langsyntaxhighlight lang="parigp">fib(n)=n--;polchebyshev(n,2,I/2)*I^n;</langsyntaxhighlight>
or
<langsyntaxhighlight lang="parigp">fib(n)=abs(polchebyshev(n-1,2,I/2));</langsyntaxhighlight>
 
===Anti-Hadamard matrix===
Line 8,819 ⟶ 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.
 
<langsyntaxhighlight lang="parigp">matantihadamard(n)={
matrix(n,n,i,j,
my(t=j-i+1);
Line 8,825 ⟶ 10,508:
);
}
fib(n)=matdet(matantihadamard(n))</langsyntaxhighlight>
 
 
===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:
<langsyntaxhighlight lang="parigp">fib(n)=
{
my(g=2^(n+1)-1);
Line 8,836 ⟶ 10,519:
bitor(i,i<<1)==g
);
}</langsyntaxhighlight>
 
===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.
<langsyntaxhighlight lang="parigp">fib(n)=my(k=0);while(n--,k++;while(!issquare(5*k^2+4)&&!issquare(5*k^2-4),k++));k</langsyntaxhighlight>
 
=={{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}}==
===Analytic===
<langsyntaxhighlight lang="pascal">function fib(n: integer):longInt;
const
Sqrt5 = sqrt(5.0);
Line 8,860 ⟶ 10,554:
else
Fibdirekt := 0
end;</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="pascal">function fib(n: integer): integer;
begin
if (n = 0) or (n = 1)
Line 8,870 ⟶ 10,564:
else
fib := fib(n-1) + fib(n-2)
end;</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight lang="pascal">function fib(n: integer): integer;
var
f0, f1, tmpf0, k: integer;
Line 8,894 ⟶ 10,588:
f1 := 0;
fib := f1;
end;</langsyntaxhighlight>
 
===Analytic2===
<langsyntaxhighlight lang="pascal">function FiboMax(n: integer):Extended; //maXbox
begin
result:= (pow((1+SQRT5)/2,n)-pow((1-SQRT5)/2,n))/SQRT5
end;</langsyntaxhighlight>
 
 
<langsyntaxhighlight lang="pascal">function Fibo_BigInt(n: integer): string; //maXbox
var tbig1, tbig2, tbig3: TInteger;
begin
Line 8,920 ⟶ 10,614:
tbig2.free;
tbig1.free;
end;</langsyntaxhighlight>
 
writeln(floattoStr(FiboMax(555)))
Line 8,928 ⟶ 10,622:
>>>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}}==
===Iterative===
<langsyntaxhighlight lang="perl">sub fib_iter {
my $n = shift;
use bigint try => "GMP,Pari";
Line 8,936 ⟶ 10,724:
($v2,$v1) = ($v1,$v2+$v1) for 0..$n;
$v1;
}</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="perl">sub fibRec {
my $n = shift;
$n < 2 ? $n : fibRec($n - 1) + fibRec($n - 2);
}</langsyntaxhighlight>
 
===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.
<langsyntaxhighlight lang="perl"># Uses GMP method so very fast
use Math::AnyNum qw/fibonacci/;
say fibonacci(10000);
Line 8,969 ⟶ 10,757:
# Perl, gives floating point *approximation*
use Math::Fibonacci qw/term/;
say term(10000);</langsyntaxhighlight>
 
===Array accumulation===
<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;
return $numbers[-1];
}
 
print "Fibonacci($_) -> ", (fibonacci $_), "\n"
foreach (0 .. 20, 50, 93, 94, 100, 200, 1000, 1476, 1477);
</syntaxhighlight>
 
{{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
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
</pre>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
Line 8,989 ⟶ 10,831:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 8,996 ⟶ 10,838:
Using native integers/atoms, errors creep in above 78, so the same program converted to use mpfr:
{{libheader|Phix/mpfr}}
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\fibonacci.exw</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 9,042 ⟶ 10,884:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 9,052 ⟶ 10,894:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">def Fibonacci
dup 0 < if
"Invalid argument: " print
Line 9,065 ⟶ 10,907:
 
10 Fibonacci pstack print nl
-10 Fibonacci print</langsyntaxhighlight>
 
=={{header|PHP}}==
===Iterative===
<langsyntaxhighlight lang="php">function fibIter($n) {
if ($n < 2) {
return $n;
Line 9,079 ⟶ 10,921:
}
return $fib;
}</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight lang="php">function fibRec($n) {
return $n < 2 ? $n : fibRec($n-1) + fibRec($n-2);
}</langsyntaxhighlight>
 
=={{header|Picat}}==
===Function===
tabling for speed.
<langsyntaxhighlight Picatlang="picat">go =>
println([fib_fun(I) : I in 1..10]),
F1=fib_fun(2**10),
Line 9,097 ⟶ 10,939:
fib_fun(0) = 0.
fib_fun(1) = 1.
fib_fun(N) = fib_fun(N-1) + fib_fun(N-2).</langsyntaxhighlight>
 
{{out}}
Line 9,104 ⟶ 10,946:
 
===Array===
<langsyntaxhighlight Picatlang="picat">fib_array(0,[0]).
fib_array(1,[0,1]).
fib_array(N,A) :-
Line 9,113 ⟶ 10,955:
foreach(I in 3..N)
A[I] = A[I-1] + A[I-2]
end.</langsyntaxhighlight>
 
===Loop===
<langsyntaxhighlight Picatlang="picat">fib_loop(N) = Curr =>
Curr = 0,
Prev = 1,
Line 9,123 ⟶ 10,965:
Curr := Curr + Prev,
Prev := Tmp
end.</langsyntaxhighlight>
 
===Formula===
{{trans|Tcl}}
Works for n <= 70.
<langsyntaxhighlight Picatlang="picat">fib_formula(N) = round((0.5 + 0.5*sqrt(5))**N / sqrt(5)).</langsyntaxhighlight>
 
==="Lazy lists"===
{{trans|Prolog}}
<langsyntaxhighlight Picatlang="picat">go =>fib_lazy(X),
A = new_list(15),
append(A,_,X),
Line 9,140 ⟶ 10,982:
ffib(0,1,X).
ffib(A,B,X) :-
freeze(X, (C is A+B, X=[C|Y], ffib(B,C,Y)) ).</langsyntaxhighlight>
 
{{out}}
Line 9,147 ⟶ 10,989:
===Generators idiom===
{{trans|Prolog}}
<langsyntaxhighlight Picatlang="picat">go =>
take(15, $fib_gen(0,1), $T-[], _G),
println(T).
Line 9,156 ⟶ 10,998:
take( N1, Next1, $B-Z, NZ).
next( fib_gen(A,B), A, fib_gen(B,C)):- C is A+B.</langsyntaxhighlight>
 
{{out}}
Line 9,172 ⟶ 11,014:
 
 
<langsyntaxhighlight Picatlang="picat">import cp.
 
go =>
Line 9,198 ⟶ 11,040:
fib_rev(N1,F1),
fib_rev(N2,F2),
F #= F1+F2.</langsyntaxhighlight>
 
{{out}}
Line 9,207 ⟶ 11,049:
=={{header|PicoLisp}}==
===Recursive===
<langsyntaxhighlight PicoLisplang="picolisp">(de fibo (N)
(if (>= 2 N)
1
(+ (fibo (dec N)) (fibo (- N 2))) ) )</langsyntaxhighlight>
 
 
Line 9,217 ⟶ 11,059:
===Recursive with Cache===
Using a recursive version doesn't need to be slow, as the following shows:
<langsyntaxhighlight PicoLisplang="picolisp">(de fibo (N)
(cache '(NIL) N # Use a cache to accelerate
(if (>= 2 N)
Line 9,223 ⟶ 11,065:
(+ (fibo (dec N)) (fibo (- N 2))) ) ) )
 
(bench (fibo 1000))</langsyntaxhighlight>
Output:
<langsyntaxhighlight PicoLisplang="picolisp">0.012 sec
-> 43466557686937456435688527675040625802564660517371780402481729089536555417949
05189040387984007925516929592259308032263477520968962323987332247116164299644090
6533187938298969649928516003704476137795166849228875</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight PicoLisplang="picolisp">(de fib (N)
(let (A 0 B 1)
(do N
(prog1 B (setq B (+ A B) A @)) ) ) )</langsyntaxhighlight>
 
===Coroutines===
<langsyntaxhighlight PicoLisplang="picolisp">(co 'fibo
(let (A 0 B 1)
(yield 'ready)
Line 9,247 ⟶ 11,089:
(printsp (yield 'next 'fibo)) )
(prinl)
(yield NIL 'fibo)</langsyntaxhighlight>
{{out}}
<pre>1 1 2 3 5 8 13 21 34 55 89 144 233 377 610</pre>
Line 9,254 ⟶ 11,096:
 
===Iterative===
<langsyntaxhighlight lang="pike">int
fibIter(int n) {
int fibPrev, fib, i;
Line 9,268 ⟶ 11,110:
}
return fib;
}</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="pike">int
fibRec(int n) {
if (n < 2) {
Line 9,277 ⟶ 11,119:
}
return( fib(n-2) + fib(n-1) );
}</langsyntaxhighlight>
 
=={{header|PIR}}==
Recursive:
{{works with|Parrot|tested with 2.4.0}}
<langsyntaxhighlight lang="pir">.sub fib
.param int n
.local int nt
Line 9,311 ⟶ 11,153:
DONE:
end
.end</langsyntaxhighlight>
 
Iterative (stack-based):
{{works with|Parrot|tested with 2.4.0}}
<langsyntaxhighlight lang="pir">.sub fib
.param int n
.local int counter
Line 9,364 ⟶ 11,206:
DONE:
end
.end</langsyntaxhighlight>
 
=={{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>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">/* 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);
Line 9,380 ⟶ 11,256:
 
end Fib;
</syntaxhighlight>
</lang>
 
=={{header|PL/M}}==
<langsyntaxhighlight lang="plm">100H:
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
Line 9,419 ⟶ 11,295:
END;
CALL EXIT;
EOF</langsyntaxhighlight>
{{out}}
<pre>0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765</pre>
Line 9,426 ⟶ 11,302:
 
=== Recursive ===
<langsyntaxhighlight SQLlang="sql">CREATE OR REPLACE FUNCTION fib(n INTEGER) RETURNS INTEGER AS $$
BEGIN
IF (n < 2) THEN
Line 9,433 ⟶ 11,309:
RETURN fib(n - 1) + fib(n - 2);
END;
$$ LANGUAGE plpgsql;</langsyntaxhighlight>
 
=== Calculated ===
<langsyntaxhighlight SQLlang="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;</langsyntaxhighlight>
 
=== Linear ===
<langsyntaxhighlight SQLlang="sql">CREATE OR REPLACE FUNCTION fibLinear(n INTEGER) RETURNS INTEGER AS $$
DECLARE
prevFib INTEGER := 0;
Line 9,459 ⟶ 11,335:
RETURN fib;
END;
$$ LANGUAGE plpgsql;</langsyntaxhighlight>
 
=== Tail recursive ===
<langsyntaxhighlight SQLlang="sql">CREATE OR REPLACE FUNCTION fibTailRecursive(n INTEGER, prevFib INTEGER DEFAULT 0, fib INTEGER DEFAULT 1)
RETURNS INTEGER AS $$
BEGIN
Line 9,470 ⟶ 11,346:
RETURN fibTailRecursive(n - 1, fib, prevFib + fib);
END;
$$ LANGUAGE plpgsql;</langsyntaxhighlight>
 
=={{header|PL/SQL}}==
<langsyntaxhighlight lang="plsql">
create or replace function fnu_fibonacci(p_num integer) return integer is
f integer;
Line 9,494 ⟶ 11,370:
end fnu_fibonacci;
/
</syntaxhighlight>
</lang>
 
=={{header|Plain English}}==
<langsyntaxhighlight lang="plainenglish">To find a fibonacci number given a count:
Put 0 into a number.
Put 1 into another number.
Line 9,504 ⟶ 11,380:
Add the number to the other number.
Swap the number with the other number.
Repeat.</langsyntaxhighlight>
 
=={{header|Pop11}}==
<langsyntaxhighlight lang="pop11">define fib(x);
lvars a , b;
1 -> a;
Line 9,515 ⟶ 11,391:
endrepeat;
a;
enddefine;</langsyntaxhighlight>
 
=={{header|PostScript}}==
Enter the desired number for "n" and run through your favorite postscript previewer or send to your postscript printer:
 
<langsyntaxhighlight lang="postscript">%!PS
 
% We want the 'n'th fibonacci number
Line 9,539 ⟶ 11,415:
(Fib\() show n (....) cvs show (\)=) show n fib (.....) cvs show
 
showpage</langsyntaxhighlight>
 
=={{header|Potion}}==
Line 9,545 ⟶ 11,421:
===Recursive===
Starts with int and upgrades on-the-fly to doubles.
<langsyntaxhighlight lang="potion">recursive = (n):
if (n <= 1): 1. else: recursive (n - 1) + recursive (n - 2)..
 
n = 40
("fib(", n, ")= ", recursive (n), "\n") join print</langsyntaxhighlight>
 
<pre>
Line 9,557 ⟶ 11,433:
 
===Iterative===
<langsyntaxhighlight lang="potion">iterative = (n) :
curr = 0
prev = 1
Line 9,567 ⟶ 11,443:
.
curr
.</langsyntaxhighlight>
 
===Matrix based===
<langsyntaxhighlight lang="potion">sqr = (x): x * x.
 
# Based on the fact that
Line 9,589 ⟶ 11,465:
.
algorithm(n)(0)
.</langsyntaxhighlight>
 
===Handling negative values===
<syntaxhighlight lang="text">fibonacci = (n) :
myFavorite = matrix
if (n >= 0) :
Line 9,604 ⟶ 11,480:
.
.
.</langsyntaxhighlight>
 
=={{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}}==
===Iterative===
<langsyntaxhighlight lang="powershell">
function FibonacciNumber ( $count )
{
Line 9,678 ⟶ 11,494:
return $answer
}
</syntaxhighlight>
</lang>
 
An even shorter version that eschews function calls altogether:
 
<langsyntaxhighlight lang="powershell">
$count = 8
$answer = @(0,1)
0..($count - $answer.Length) | Foreach { $answer += $answer[-1] + $answer[-2] }
$answer
</syntaxhighlight>
</lang>
 
===Recursive===
<langsyntaxhighlight lang="powershell">function fib($n) {
switch ($n) {
0 { return 0 }
Line 9,697 ⟶ 11,513:
default { return (fib ($n - 1)) + (fib ($n - 2)) }
}
}</langsyntaxhighlight>
 
=={{header|Processing}}==
{{trans|Java}}
<langsyntaxhighlight lang="processing">void setup() {
size(400, 400);
fill(255, 64);
Line 9,714 ⟶ 11,530:
int fibonacciNum(int n) {
return (n < 2) ? n : fibonacciNum(n - 1) + fibonacciNum(n - 2);
}</langsyntaxhighlight>
 
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.
Line 9,738 ⟶ 11,554:
{{works with|GNU Prolog}}
{{works with|YAP}}
<langsyntaxhighlight lang="prolog">
fib(1, 1) :- !.
fib(0, 0) :- !.
Line 9,745 ⟶ 11,561:
B is N - 2, fib(B, 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):
<langsyntaxhighlight lang="prolog">?- time(fib(0,F)).
% 2 inferences, 0.000 CPU in 0.000 seconds (88% CPU, 161943 Lips)
F = 0.
Line 9,766 ⟶ 11,582:
?- time(fib(40,F)).
% 496,740,421 inferences, 138.705 CPU in 140.206 seconds (99% CPU, 3581264 Lips)
F = 102334155.</langsyntaxhighlight>
 
As you can see, the calculation time goes up exponentially as N goes higher.
Line 9,776 ⟶ 11,592:
 
The performance problem can be readily fixed by the addition of two lines of code (the first and last in this version):
<langsyntaxhighlight 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.
fib(1, 1) :- !.
Line 9,784 ⟶ 11,600:
B is N - 2, fib(B, B1),
Value is A1 + B1,
asserta((fib(N, Value) :- !)).</langsyntaxhighlight>
 
Let's take a look at the execution costs now:
 
<langsyntaxhighlight lang="prolog">?- time(fib(0,F)).
% 2 inferences, 0.000 CPU in 0.000 seconds (90% CPU, 160591 Lips)
F = 0.
Line 9,806 ⟶ 11,622:
?- time(fib(40,F)).
% 41 inferences, 0.000 CPU in 0.000 seconds (96% CPU, 543572 Lips)
F = 102334155.</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="prolog">?- listing(fib).
:- dynamic fib/2.
 
Line 9,860 ⟶ 11,676:
fib(C, F),
D is E+F,
asserta((fib(A, D):-!)).</langsyntaxhighlight>
 
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 9,866 ⟶ 11,682:
===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
<langsyntaxhighlight Prologlang="prolog">:- use_module(lambda).
fib(N, FN) :-
cont_fib(N, _, FN, \_^Y^_^U^(U = Y)).
Line 9,879 ⟶ 11,695:
call(Pred, FNA, FNB, FN1, FN)
).
</syntaxhighlight>
</lang>
 
===With lazy lists===
Works with <b>SWI-Prolog</b> and others that support <code>freeze/2</code>.
 
<langsyntaxhighlight Prologlang="prolog">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)) ).</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight Prologlang="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]</langsyntaxhighlight>
 
===Generators idiom===
 
<langsyntaxhighlight Prologlang="prolog">take( 0, Next, Z-Z, Next).
take( N, Next, [A|B]-Z, NZ):- N>0, !, next( Next, A, Next1),
N1 is N-1,
Line 9,905 ⟶ 11,721:
%% 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)</langsyntaxhighlight>
 
=== 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.
 
<langsyntaxhighlight Prologlang="prolog">% 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).
Line 9,916 ⟶ 11,732:
fib(0, 0).
fib(1, 1).
fib(C, N) :- fib(2, [0,1], C, N). % Generate from 3rd sequence on</langsyntaxhighlight>
Looking at performance:
<pre> ?- time(fib(30,X)).
Line 9,960 ⟶ 11,776:
 
=== Efficient implementation ===
<syntaxhighlight lang="prolog">
<lang Prolog>
% John Devou: 26-Nov-2021
% Efficient program to calculate n-th Fibonacci number.
Line 9,973 ⟶ 11,789:
 
fib(N,F):- b(N,[],Bs), f(Bs,0,1,2,F), !.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 9,995 ⟶ 11,811:
=={{header|Pure}}==
===Tail Recursive===
<langsyntaxhighlight 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;</langsyntaxhighlight>
 
=={{header|PureBasic}}==
 
===Macro based calculation===
<lang PureBasic>Macro Fibonacci (n)
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>
 
===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
<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>
 
'''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|Purity}}==
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
<
Line 10,069 ⟶ 11,824:
(uncurry Cons) . ((uncurry Add) . (Head, Head . Tail), id)
>
</syntaxhighlight>
</lang>
 
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?
data Fib2 = Unfold ((outl, (uncurry Add, outl))) ((curry id) One One)
</syntaxhighlight>
</lang>
 
As a histomorphism:
 
<syntaxhighlight lang="purity">
<lang Purity>
import Histo
 
Line 10,092 ⟶ 11,847:
> (outr $p1)) . UnmakeCofree
>
</syntaxhighlight>
</lang>
 
=={{header|Python}}==
===Analytic===
Binet's formula:
<langsyntaxhighlight lang="python">from math import *
 
def analytic_fibonacci(n):
Line 10,106 ⟶ 11,861:
 
for i in range(1,31):
print analytic_fibonacci(i),</langsyntaxhighlight>
Output:
<pre>
Line 10,113 ⟶ 11,868:
 
===Iterative===
<langsyntaxhighlight lang="python">def fibIter(n):
if n < 2:
return n
Line 10,120 ⟶ 11,875:
for _ in range(2, n):
fibPrev, fib = fib, fib + fibPrev
return fib</langsyntaxhighlight>
 
====Iterative positive and negative====
<langsyntaxhighlight 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),</langsyntaxhighlight>
Output:
<pre>
Line 10,136 ⟶ 11,891:
 
===Recursive===
<langsyntaxhighlight lang="python">def fibRec(n):
if n < 2:
return n
else:
return fibRec(n-1) + fibRec(n-2)</langsyntaxhighlight>
 
===Recursive with Memoization===
 
<langsyntaxhighlight lang="python">def fibMemo():
pad = {0:0, 1:1}
def func(n):
Line 10,154 ⟶ 11,909:
fm = fibMemo()
for i in range(1,31):
print fm(i),</langsyntaxhighlight>
 
Output:
Line 10,166 ⟶ 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:
 
<langsyntaxhighlight lang="python">def fibFastRec(n):
def fib(prvprv, prv, c):
if c < 1:
Line 10,172 ⟶ 11,927:
else:
return fib(prv, prvprv + prv, c - 1)
return fib(0, 1, n)</langsyntaxhighlight>
 
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===
<langsyntaxhighlight lang="python">def fibGen(n):
a, b = 0, 1
while n>0:
yield a
a, b, n = b, a+b, n-1</langsyntaxhighlight>
====Example use====
<langsyntaxhighlight lang="python">
>>> [i for i in fibGen(11)]
 
[0,1,1,2,3,5,8,13,21,34,55]
</syntaxhighlight>
</lang>
 
===Matrix-Based===
Translation of the matrix-based approach used in F#.
<langsyntaxhighlight lang="python">
def prevPowTwo(n):
'Gets the power of two that is less than or equal to the given input'
Line 10,222 ⟶ 11,977:
return q
</syntaxhighlight>
</lang>
 
===Large step recurrence===
This is much faster for a single, large value of n:
<langsyntaxhighlight lang="python">def fib(n, c={0:1, 1:1}):
if n not in c:
x = n // 2
Line 10,232 ⟶ 11,987:
return c[n]
 
fib(10000000) # calculating it takes a few seconds, printing it takes eons</langsyntaxhighlight>
 
===Same as above but slightly faster===
Putting the dictionary outside the function makes this about 2 seconds faster, could just make a wrapper:
<langsyntaxhighlight lang="python">F = {0: 0, 1: 1, 2: 1}
def fib(n):
if n in F:
Line 10,243 ⟶ 11,998:
f2 = fib((n - 1) // 2)
F[n] = (f1 * f1 + f2 * f2 if n & 1 else f1 * f1 - f2 * f2)
return F[n]</langsyntaxhighlight>
 
===Generative with Recursion===
This can get very slow and uses a lot of memory. Can be sped up by caching the generator results.
<langsyntaxhighlight lang="python">def fib():
"""Yield fib[n+1] + fib[n]"""
yield 1 # have to start somewhere
Line 10,256 ⟶ 12,011:
 
f=fib()
print [next(f) for _ in range(9)]</langsyntaxhighlight>
 
Output:
Line 10,262 ⟶ 12,017:
 
'''Another version of recursive generators solution, starting from 0'''
<langsyntaxhighlight Pythonlang="python">from itertools import islice
 
def fib():
Line 10,272 ⟶ 12,027:
yield next(a)+next(b)
print(tuple(islice(fib(), 10)))</langsyntaxhighlight>
 
===As a scan or a fold ===
Line 10,278 ⟶ 12,033:
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}}
<langsyntaxhighlight lang="python">'''Fibonacci accumulation'''
 
from itertools import accumulate, chain
Line 10,308 ⟶ 12,063:
fibs(20)
)
)</langsyntaxhighlight>
{{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>
Line 10,316 ⟶ 12,071:
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}}
<langsyntaxhighlight lang="python">'''Nth Fibonacci term (by folding)'''
 
from functools import reduce
Line 10,336 ⟶ 12,091:
nthFib(1000)
)
)</langsyntaxhighlight>
{{Out}}
<pre>1000th term: 43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875</pre>
 
{{Works with|Python|3.9}}
<langsyntaxhighlight 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>
</lang>
 
===Array and Range===
<langsyntaxhighlight 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)</langsyntaxhighlight>
 
{{Out}}
Line 10,360 ⟶ 12,115:
 
===Minimal from Russia===
<langsyntaxhighlight lang="python">fi1=fi2=fi3=1 # FIB Russia rextester.com/FEEJ49204
for da in range(1, 88): # Danilin
print("."*(20-len(str(fi3))), end=' ')
Line 10,366 ⟶ 12,121:
fi3 = fi2+fi1
fi1 = fi2
fi2 = fi3</langsyntaxhighlight>
 
{{Out}}
Line 10,380 ⟶ 12,135:
.. 679891637638612258
. 1100087778366101931</pre>
 
=={{header|QB64}}==
''CBTJD'': 2020/03/13
<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
</lang>
 
=={{header|Qi}}==
===Recursive===
<syntaxhighlight lang="qi">
<lang qi>
(define fib
0 -> 0
Line 10,426 ⟶ 12,144:
N -> (+ (fib-r (- N 1))
(fib-r (- N 2))))
</syntaxhighlight>
</lang>
===Iterative===
<syntaxhighlight lang="qi">
<lang qi>
(define fib-0
V2 V1 0 -> V2
Line 10,435 ⟶ 12,153:
(define fib
N -> (fib-0 0 1 N))
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ 0 1 rot times [ tuck + ] drop ] is fibo ( n --> n )
 
100 fibo echo</langsyntaxhighlight>
 
{{out}}
Line 10,449 ⟶ 12,167:
=={{header|R}}==
===Iterative positive and negative===
<langsyntaxhighlight 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 (n<0) return(x[2]*(-1)^(abs(n)-1)) else if (n) return(x[2]) else return(0)
}
 
sapply(seq(-31,31),fib)</langsyntaxhighlight>
Output:
<pre>
Line 10,466 ⟶ 12,184:
</pre>
===Other methods===
<langsyntaxhighlight Rlang="r"># recursive
recfibo <- function(n) {
if ( n < 2 ) n
Line 10,504 ⟶ 12,222:
}
 
print.table(lapply(0:20, funcfibo))</langsyntaxhighlight>
 
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 10,514 ⟶ 12,232:
 
=={{header|Ra}}==
<syntaxhighlight lang="ra">
<lang Ra>
class FibonacciSequence
**Prints the nth fibonacci number**
Line 10,560 ⟶ 12,278:
return a
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
 
===Tail Recursive===
<syntaxhighlight lang="racket">
<lang Racket>
(define (fib n)
(let loop ((cnt 0) (a 0) (b 1))
Line 10,571 ⟶ 12,289:
a
(loop (+ cnt 1) b (+ a b)))))
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="racket">
<lang Racket>
(define (fib n (a 0) (b 1))
(if (< n 2)
1
(+ a (fib (- n 1) b (+ a b)))))
</syntaxhighlight>
</lang>
 
===Matrix Form===
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 10,593 ⟶ 12,311:
 
(fibmat 1000)
</syntaxhighlight>
</lang>
 
===Foldl Form===
<syntaxhighlight lang="racket">
<lang Racket>
(define (fib n)
(car (foldl (lambda (y x)
(let ((a (car x)) (b (cdr x)))
(cons b (+ a b)))) (cons 0 1) (range n))))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 10,609 ⟶ 12,327:
 
This constructs the fibonacci sequence as a lazy infinite list.
<syntaxhighlight lang="raku" perl6line>constant @fib = 0, 1, *+* ... *;</langsyntaxhighlight>
 
If you really need a function for it:
<syntaxhighlight lang="raku" perl6line>sub fib ($n) { @fib[$n] }</langsyntaxhighlight>
 
To support negative indices:
<syntaxhighlight lang="raku" perl6line>constant @neg-fib = 0, 1, *-* ... *;
sub fib ($n) { $n >= 0 ?? @fib[$n] !! @neg-fib[-$n] }</langsyntaxhighlight>
 
===Iterative===
<syntaxhighlight lang="raku" perl6line>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;
}</langsyntaxhighlight>
 
===Recursive===
<syntaxhighlight lang="raku" perl6line>proto fib (Int $n --> Int) {*}
multi fib (0) { 0 }
multi fib (1) { 1 }
multi fib ($n) { fib($n - 1) + fib($n - 2) }</langsyntaxhighlight>
 
=={{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\
>$.@</langsyntaxhighlight>
 
=={{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 []
<lang Red>palindrome: [fn: fn-1 + fn-1: fn]
 
palindrome: [fn: fn-1 + fn-1: fn]
fibonacci: func [n][
fn-1: 0
fn: 1
loop n palindrome
]</langsyntaxhighlight>
 
=={{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">
<lang Relation>
function fibonacci (n)
if n < 2
Line 10,662 ⟶ 12,441:
end if
end function
</syntaxhighlight>
</lang>
 
=={{header|Retro}}==
===Recursive===
<langsyntaxhighlight Retrolang="retro">: fib ( n-m ) dup [ 0 = ] [ 1 = ] bi or if; [ 1- fib ] sip [ 2 - fib ] do + ;</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight Retrolang="retro">: fib ( n-N )
[ 0 1 ] dip [ over + swap ] times drop ;</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 10,677 ⟶ 12,456:
 
This version of the REXX program can also handle &nbsp; ''negative'' &nbsp; Fibonacci numbers.
<langsyntaxhighlight lang="rexx">/*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. */
Line 10,699 ⟶ 12,478:
/* [↓] 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*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre style="height:150ex">
Line 10,792 ⟶ 12,571:
Fibonacci(10000) has a length of 2090 decimal digits
</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}}==
<langsyntaxhighlight lang="ring">
give n
x = fib(n)
Line 10,802 ⟶ 12,633:
if nr = 1 return 1 ok
if nr > 1 return fib(nr-1) + fib(nr-2) ok
</syntaxhighlight>
</lang>
 
=={{header|Rockstar}}==
===Iterative (minimized)===
<syntaxhighlight lang="rockstar">
<lang Rockstar>
Fibonacci takes Number
FNow is 0
Line 10,817 ⟶ 12,648:
 
Say Fibonacci taking 1000 (prints out highest number in Fibonacci sequence less than 1000)
</syntaxhighlight>
</lang>
 
===Iterative (idiomatic)===
<syntaxhighlight lang="rockstar">
<lang Rockstar>
Love takes Time
My love was addictions
Line 10,833 ⟶ 12,664:
 
Shout; Love taking 1000 (years, years)
</syntaxhighlight>
</lang>
 
The semicolon and the comment <code>(years, years)</code> in this version are there only for poetic effect
 
===Recursive===
<syntaxhighlight lang="rockstar">
<lang Rockstar>
The Italian takes a lover, a kiss, a promise
love is population
Line 10,856 ⟶ 12,687:
your soul is opportunity
Whisper The Italian taking your heart, your mind, your soul
</syntaxhighlight>
</lang>
 
=={{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}}==
===Iterative===
<langsyntaxhighlight lang="ruby">def fib(n)
if n < 2
n
Line 10,872 ⟶ 12,734:
end
 
p (0..10).map { |i| fib(i) }</langsyntaxhighlight>
Output:
<pre>
Line 10,879 ⟶ 12,741:
 
===Recursive===
<langsyntaxhighlight lang="ruby">def fib(n, sequence=[1])
return sequence.last if n == 0
 
Line 10,887 ⟶ 12,749:
fib(n-1, sequence)
end
</syntaxhighlight>
</lang>
 
===Recursive with Memoization===
<langsyntaxhighlight lang="ruby"># Use the Hash#default_proc feature to
# lazily calculate the Fibonacci numbers.
 
Line 10,902 ⟶ 12,764:
end
end
# examples: fib[10] => 55, fib[-10] => (-55/1)</langsyntaxhighlight>
 
===Matrix===
<langsyntaxhighlight lang="ruby">require 'matrix'
 
# To understand why this matrix is useful for Fibonacci numbers, remember
Line 10,940 ⟶ 12,802:
return nil if matrix.row_size == 0
return matrix[matrix.row_size - 1, matrix.column_size - 1]
end</langsyntaxhighlight>
 
===Generative===
<langsyntaxhighlight lang="ruby">fib = Enumerator.new do |y|
f0, f1 = 0, 1
loop do
Line 10,949 ⟶ 12,811:
f0, f1 = f1, f0 + f1
end
end</langsyntaxhighlight>
 
Usage:
Line 10,958 ⟶ 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]
 
<langsyntaxhighlight lang="ruby">fib = Fiber.new do
a,b = 0,1
loop do
Line 10,965 ⟶ 12,827:
end
end
9.times {puts fib.resume}</langsyntaxhighlight>
 
using a lambda
<langsyntaxhighlight lang="ruby">def fib_gen
a, b = 1, 1
lambda {ret, a, b = a, b, a+b; ret}
end</langsyntaxhighlight>
 
<pre>
Line 10,990 ⟶ 12,852:
 
===Binet's Formula===
<langsyntaxhighlight lang="ruby">def fib
phi = (1 + Math.sqrt(5)) / 2
((phi**self - (-1 / phi)**self) / Math.sqrt(5)).to_i
end</langsyntaxhighlight>
<pre>
1.9.3p125 :001 > def fib
Line 11,003 ⟶ 12,865:
=> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
</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}}==
===Iterative===
<langsyntaxhighlight lang="rust">fn main() {
let mut prev = 0;
// Rust needs this type hint for the checked_add method
Line 11,036 ⟶ 12,878:
println!("{}", n);
}
}</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="rust">use std::mem;
fn main() {
fibonacci(0,1);
Line 11,050 ⟶ 12,892:
fibonacci(prev, n);
}
}</langsyntaxhighlight>
 
===Recursive (with pattern matching)===
<langsyntaxhighlight lang="rust">fn fib(n: u32) -> u32 {
match n {
0 => 0,
Line 11,059 ⟶ 12,901:
n => fib(n - 1) + fib(n - 2),
}
}</langsyntaxhighlight>
 
===Tail recursive (with pattern matching)===
<langsyntaxhighlight lang="rust">fn fib_tail_recursive(nth: usize) -> usize {
fn fib_tail_iter(n: usize, prev_fib: usize, fib: usize) -> usize {
match n {
Line 11,070 ⟶ 12,912:
}
fib_tail_iter(nth, 0, 1)
}</langsyntaxhighlight>
 
===Analytic===
<langsyntaxhighlight lang="rust">fn main() {
for num in fibonacci_sequence() {
println!("{}", num);
Line 11,085 ⟶ 12,927:
// 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))
}</langsyntaxhighlight>
 
===Using an Iterator===
Iterators are very idiomatic in rust, though they may be overkill for such a simple problem.
<langsyntaxhighlight lang="rust">use std::mem;
 
struct Fib {
Line 11,117 ⟶ 12,959:
println!("{}", num);
}
}</langsyntaxhighlight>
 
 
====Iterator "Successors"====
<langsyntaxhighlight 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));
}</langsyntaxhighlight>
 
=={{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 basic>
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
</lang>
{{out}}
<pre> 0 1 1 2 3 5 8 13 21 34 55
</pre>
 
=={{header|SAS}}==
 
=== Iterative ===
 
This code builds a table <code>fib</code> holding the first few values of the Fibonacci sequence.
<syntaxhighlight lang="sas">data fib;
 
<lang sas>data fib;
a=0;
b=1;
Line 11,172 ⟶ 12,982:
end;
keep n f;
run;</langsyntaxhighlight>
 
=== 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.
 
<langsyntaxhighlight lang="sas">options cmplib=work.f;
 
proc fcmp outlib=work.f.p;
Line 11,191 ⟶ 13,000:
x = fib(5);
put 'fib(5) = ' x;
run;</langsyntaxhighlight>
 
=={{header|Sather}}==
The implementations use the arbitrary precision class INTI.
<langsyntaxhighlight lang="sather">class MAIN is
 
-- RECURSIVE --
Line 11,228 ⟶ 13,037:
end;
 
end;</langsyntaxhighlight>
 
=={{header|Scala}}==
===Recursive===
<langsyntaxhighlight lang="scala">def fib(i: Int): Int = i match {
case 0 => 0
case 1 => 1
case _ => fib(i - 1) + fib(i - 2)
}</langsyntaxhighlight>
 
===Lazy sequence===
<langsyntaxhighlight lang="scala">lazy val fib: LazyList[Int] = 0 #:: 1 #:: fib.zip(fib.tail).map { case (a, b) => a + b }</langsyntaxhighlight>
 
===Tail recursive===
<langsyntaxhighlight lang="scala">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)
}</langsyntaxhighlight>
 
===foldLeft===
<langsyntaxhighlight 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
def fib(n: Int): BigInt = {
Line 11,263 ⟶ 13,072:
 
// result: 0 1 1 2 3 5 8 13 21 34 55 89 144 233
</syntaxhighlight>
</lang>
 
===Iterator===
<langsyntaxhighlight lang="scala">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</langsyntaxhighlight>
 
=={{header|Scheme}}==
===Iterative===
<langsyntaxhighlight lang="scheme">(define (fib-iter n)
(do ((num 2 (+ num 1))
(fib-prev 1 fib)
(fib 1 (+ fib fib-prev)))
((>= num n) fib)))</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="scheme">(define (fib-rec n)
(if (< n 2)
n
(+ (fib-rec (- n 1))
(fib-rec (- n 2)))))</langsyntaxhighlight>
 
This version is tail recursive:
<langsyntaxhighlight lang="scheme">(define (fib n)
(let loop ((a 0) (b 1) (n n))
(if (= n 0) a
(loop b (+ a b) (- n 1)))))
</syntaxhighlight>
</lang>
 
===Recursive Sequence Generator===
Line 11,301 ⟶ 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):
 
<langsyntaxhighlight lang="scheme">
(define (fib)
(define (nxt lv nv) (cons nv (lambda () (nxt nv (+ lv nv)))))
Line 11,311 ⟶ 13,120:
(if (> n 1) (begin (display " ") (shw-nxt (- n 1) ((cdr strm)))) (display ")"))))
(begin (display "(") (shw-nxt n strm)))
(show-stream-take 30 (fib))</langsyntaxhighlight>
 
{{output}}
Line 11,317 ⟶ 13,126:
 
===Dijkstra Algorithm===
<langsyntaxhighlight lang="scheme">;;; Fibonacci numbers using Edsger Dijkstra's algorithm
;;; http://www.cs.utexas.edu/users/EWD/ewd06xx/EWD654.PDF
 
Line 11,335 ⟶ 13,144:
q
(- count 1)))))
(fib-aux 1 0 0 1 n))</langsyntaxhighlight>
 
=={{header|Scilab}}==
<syntaxhighlight lang="text"> clear
n=46
f1=0; f2=1
Line 11,348 ⟶ 13,157:
f1=f2
f2=f3
end</langsyntaxhighlight>
{{out}}
<pre>...
Line 11,357 ⟶ 13,166:
 
=={{header|sed}}==
<langsyntaxhighlight lang="sed">#!/bin/sed -f
 
# First we need to convert each number into the right number of ticks
Line 11,396 ⟶ 13,205:
s/</|/g
t back
s/^$/0/</langsyntaxhighlight>
 
=={{header|Seed7}}==
===Recursive===
<langsyntaxhighlight lang="seed7">const func integer: fib (in integer: number) is func
result
var integer: result is 1;
Line 11,409 ⟶ 13,218:
result := 0;
end if;
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/math.htm#fib]
Line 11,416 ⟶ 13,225:
This funtion uses a bigInteger result:
 
<langsyntaxhighlight lang="seed7">const func bigInteger: fib (in integer: number) is func
result
var bigInteger: result is 1_;
Line 11,429 ⟶ 13,238:
result +:= c;
end for;
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/math.htm#iterative_fib]
Line 11,435 ⟶ 13,244:
=={{header|SequenceL}}==
===Recursive===
<langsyntaxhighlight lang="sequencel">fibonacci(n) :=
n when n < 2
else
fibonacci(n - 1) + fibonacci(n - 2);</langsyntaxhighlight>
Based on: [https://www.youtube.com/watch?v=5JVC5dDtnyg]
 
===Tail Recursive===
<langsyntaxhighlight lang="sequencel">fibonacci(n) := fibonacciHelper(0, 1, n);
fibonacciHelper(prev, next, n) :=
Line 11,449 ⟶ 13,258:
next when n = 1
else
fibonacciHelper(next, next + prev, n - 1);</langsyntaxhighlight>
 
===Matrix===
<langsyntaxhighlight lang="sequencel">fibonacci(n) := fibonacciHelper([[1,0],[0,1]], n);
 
fibonacciHelper(M(2), n) :=
Line 11,462 ⟶ 13,271:
fibonacciHelper(matmul(M, N), n - 1);
 
matmul(A(2), B(2)) [i,j] := sum( A[i,all] * B[all,j] );</langsyntaxhighlight>
Based on the C# version: [http://rosettacode.org/wiki/Fibonacci_sequence#C.23]
 
Line 11,468 ⟶ 13,277:
 
=={{header|SETL}}==
<langsyntaxhighlight lang="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}'
Line 11,482 ⟶ 13,291:
end loop;
return C;
end proc;</langsyntaxhighlight>
 
=={{header|Shen}}==
<langsyntaxhighlight Shenlang="shen">(define fib
0 -> 0
1 -> 1
N -> (+ (fib (+ N 1)) (fib (+ N 2)))
where (< N 0)
N -> (+ (fib (- N 1)) (fib (- N 2))))</langsyntaxhighlight>
 
=={{header|Sidef}}==
===Iterative===
<langsyntaxhighlight lang="ruby">func fib_iter(n) {
var (a, b) = (0, 1)
{ (a, b) = (b, a+b) } * n
return a
}</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="ruby">func fib_rec(n) {
n < 2 ? n : (__FUNC__(n-1) + __FUNC__(n-2))
}</langsyntaxhighlight>
 
===Recursive with memoization===
<langsyntaxhighlight lang="ruby">func fib_mem (n) is cached {
n < 2 ? n : (__FUNC__(n-1) + __FUNC__(n-2))
}</langsyntaxhighlight>
 
===Closed-form===
<langsyntaxhighlight lang="ruby">func fib_closed(n) {
define S = (1.25.sqrt + 0.5)
define T = (-S + 1)
(S**n - T**n) / (-T + S) -> round
}</langsyntaxhighlight>
 
===Built-in===
<langsyntaxhighlight lang="ruby">say fib(12) #=> 144</langsyntaxhighlight>
 
=={{header|Simula}}==
Straightforward iterative implementation.
<langsyntaxhighlight lang="simula">INTEGER PROCEDURE fibonacci(n);
INTEGER n;
BEGIN
Line 11,535 ⟶ 13,344:
END;
fibonacci := hi
END;</langsyntaxhighlight>
 
=={{header|SkookumScript}}==
Line 11,543 ⟶ 13,352:
SkookumScript's <code>Integer</code> class has a fast built-in <code>fibonnaci()</code> method.
 
<syntaxhighlight lang ="javascript">42.fibonacci</langsyntaxhighlight>
 
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 11,551 ⟶ 13,360:
Simple recursive method in same <code>42.fibonacci</code> form as built-in form above.
 
<langsyntaxhighlight lang="javascript">// Assuming code is in Integer.fibonacci() method
() Integer
[
if this < 2 [this] else [[this - 1].fibonacci + [this - 2].fibonacci]
]</langsyntaxhighlight>
 
Recursive procedure in <code>fibonacci(42)</code> form.
 
<langsyntaxhighlight lang="javascript">// Assuming in fibonacci(n) procedure
(Integer n) Integer
[
if n < 2 [n] else [fibonacci(n - 1) + fibonacci(n - 2)]
]</langsyntaxhighlight>
 
===Iterative===
Line 11,569 ⟶ 13,378:
Iterative method in <code>42.fibonacci</code> form.
 
<langsyntaxhighlight lang="javascript">// Assuming code is in Integer.fibonacci() method
() Integer
[
Line 11,587 ⟶ 13,396:
next
]
]</langsyntaxhighlight>
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.
 
<langsyntaxhighlight lang="javascript">// Bind : is faster than assignment :=
// loop is faster than to_pre (which uses a closure)
() Integer
Line 11,615 ⟶ 13,424:
next
]
]</langsyntaxhighlight>
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">n@(Integer traits) fib
[
n <= 0 ifTrue: [^ 0].
Line 11,626 ⟶ 13,435:
 
slate[15]> 10 fib = 55.
True</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
Line 11,636 ⟶ 13,445:
 
iterative (slow):
<langsyntaxhighlight lang="smalltalk">Integer >> fibI
|aNMinus1 an t|
 
Line 11,646 ⟶ 13,455:
aNMinus1 := t.
].
^ an</langsyntaxhighlight>
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):
<langsyntaxhighlight lang="smalltalk">Integer >> fibR
(self > 1) ifTrue:[
^ (self - 1) fibR + (self - 2) fibR
].
^ self</langsyntaxhighlight>
analytic (fast, but inexact, and limited to small n below 1475 if we use double precision IEEE floats):
<langsyntaxhighlight lang="smalltalk">Integer >> fibBinet
|phi rPhi|
 
Line 11,661 ⟶ 13,470:
rPhi := 1 / phi.
 
^ (1 / 5 sqrt) * ((phi raisedTo:self) - (rPhi raisedTo:self))</langsyntaxhighlight>
using more bits in the exponent, we can compute larger fibs (up to 23599 with x86 extended precision floats), but still inexact:
<langsyntaxhighlight lang="smalltalk">Integer >> fibBinetFloatE
|phi rPhi|
 
Line 11,669 ⟶ 13,478:
rPhi := 1 / phi.
 
^ (1 / 5 sqrt) * ((phi raisedTo:self) - (rPhi raisedTo:self))</langsyntaxhighlight>
<langsyntaxhighlight lang="smalltalk">
(10 to:1e6 byFactor:10) do:[:n |
Transcript printCR:'----',n,'----'.
Line 11,695 ⟶ 13,504:
[ 1000000 fib ] benchmark:'1000000 fib (builtin)'.
[ 2000000 fib ] benchmark:'2000000 fib (builtin)'.
[ 10000000 fib ] benchmark:'10000000 fib (builtin)'</langsyntaxhighlight>
{{out}}
<pre>----10----
Line 11,743 ⟶ 13,552:
2000000 fib (builtin): 229ms (827461038 cycles)
10000000 fib (builtin): 2.769s (9970686190 cycles)</pre>
 
=={{header|smart BASIC}}==
 
The Iterative method is slow (relatively) and the Recursive method doubly so since it references the Iterative 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>
 
<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</lang>
 
=={{header|SNOBOL4}}==
 
===Recursive===
<langsyntaxhighlight lang="snobol"> define("fib(a)") :(fib_end)
fib fib = lt(a,2) a :s(return)
fib = fib(a - 1) + fib(a - 2) :(return)
Line 11,798 ⟶ 13,562:
while a = trim(input) :f(end)
output = a " " fib(a) :(while)
end</langsyntaxhighlight>
 
===Tail-recursive===
<langsyntaxhighlight SNOBOL4lang="snobol4"> 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</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight SNOBOL4lang="snobol4"> 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</langsyntaxhighlight>
 
===Analytic===
Line 11,819 ⟶ 13,583:
Note: Snobol4+ lacks built-in sqrt( ) function.
 
<langsyntaxhighlight SNOBOL4lang="snobol4"> 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</langsyntaxhighlight>
 
Test and display all, Fib 1 .. 10
 
<langsyntaxhighlight SNOBOL4lang="snobol4">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</langsyntaxhighlight>
 
Output:
Line 11,843 ⟶ 13,607:
 
===Iterative===
<langsyntaxhighlight lang="snusp"> @!\+++++++++# /<<+>+>-\
fib\==>>+<<?!/>!\ ?/\
#<</?\!>/@>\?-<<</@>/@>/>+<-\
\-/ \ !\ !\ !\ ?/#</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="snusp"> /========\ />>+<<-\ />+<-\
fib==!/?!\-?!\->+>+<<?/>>-@\=====?/<@\===?/<#
| #+==/ fib(n-2)|+fib(n-1)|
\=====recursion======/!========/</langsyntaxhighlight>
 
=={{header|Softbridge BASIC}}==
===Iterative===
<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
</lang>
 
=={{header|Spin}}==
Line 11,883 ⟶ 13,624:
{{works with|HomeSpun}}
{{works with|OpenSpin}}
<langsyntaxhighlight lang="spin">con
_clkmode = xtal1 + pll16x
_clkfreq = 80_000_000
Line 11,904 ⟶ 13,645:
b := a := 1
repeat i
a := b + (b := a)</langsyntaxhighlight>
{{out}}
<pre>1 1 2 3 5 8 13 21 34 55 89</pre>
Line 11,910 ⟶ 13,651:
=={{header|SPL}}==
=== Analytic ===
<langsyntaxhighlight lang="spl">fibo(n)=
s5 = #.sqrt(5)
<= (((1+s5)/2)^n-((1-s5)/2)^n)/s5
.</langsyntaxhighlight>
=== Iterative ===
<langsyntaxhighlight lang="spl">fibo(n)=
? n<2, <= n
f2 = 0
Line 11,925 ⟶ 13,666:
<
<= f
.</langsyntaxhighlight>
=== Recursive ===
<langsyntaxhighlight lang="spl">fibo(n)=
? n<2, <= n
<= fibo(n-1)+fibo(n-2)
.</langsyntaxhighlight>
 
=={{header|SQL}}==
=== Analytic ===
As a running sum:
<syntaxhighlight lang="sql">
<lang SQL>
select round ( exp ( sum (ln ( ( 1 + sqrt( 5 ) ) / 2)
) over ( order by level ) ) / sqrt( 5 ) ) fibo
from dual
connect by level <= 10;
</syntaxhighlight>
</lang>
<pre>
FIB
Line 11,958 ⟶ 13,699:
</pre>
As a power:
<syntaxhighlight lang="sql">
<lang SQL>
select round ( power( ( 1 + sqrt( 5 ) ) / 2, level ) / sqrt( 5 ) ) fib
from dual
connect by level <= 10;
</syntaxhighlight>
</lang>
<pre>
FIB
Line 11,984 ⟶ 13,725:
 
Oracle 12c required
<langsyntaxhighlight 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;
 
Line 12,001 ⟶ 13,742:
 
10 rows selected.
</syntaxhighlight>
</lang>
 
{{works with|PostgreSQL}}
 
<langsyntaxhighlight lang="postgresql">CREATE FUNCTION fib(n int) RETURNS numeric AS $$
-- This recursive with generates endless list of Fibonacci numbers.
WITH RECURSIVE fibonacci(current, previous) AS (
Line 12,031 ⟶ 13,772:
-- position in the list.
OFFSET n
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT IMMUTABLE;</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="ssem">10101000000000100000000000000000 0. -21 to c acc = -n
01101000000001100000000000000000 1. c to 22 temp = acc
00101000000001010000000000000000 2. Sub. 20 acc -= m
Line 12,060 ⟶ 13,801:
10010000000000000000000000000000 23. 9 var count = 9
11111111111111111111111111111111 24. -1 const -1
11110000000000000000000000000000 25. 15 const 15</langsyntaxhighlight>
 
=={{header|Stata}}==
 
<langsyntaxhighlight lang="stata">program fib
args n
clear
Line 12,070 ⟶ 13,811:
qui gen a=1
qui replace a=a[_n-1]+a[_n-2] in 3/l
end</langsyntaxhighlight>
 
An implementation using '''[https://www.stata.com/help.cgi?dyngen dyngen]'''.
 
<langsyntaxhighlight lang="stata">program fib
args n
clear
Line 12,085 ⟶ 13,826:
 
fib 10
list</langsyntaxhighlight>
 
'''Output'''
Line 12,106 ⟶ 13,847:
 
=== Mata ===
<langsyntaxhighlight lang="stata">. mata
: function fib(n) {
return((((1+sqrt(5))/2):^n-((1-sqrt(5))/2):^n)/sqrt(5))
Line 12,117 ⟶ 13,858:
+--------------------------------------------------------+
 
: end</langsyntaxhighlight>
 
=={{header|StreamIt}}==
<langsyntaxhighlight lang="streamit">void->int feedbackloop Fib {
join roundrobin(0,1);
body in->int filter {
Line 12,129 ⟶ 13,870:
enqueue(0);
enqueue(1);
}</langsyntaxhighlight>
 
=={{header|SuperCollider}}==
===Recursive===
nth fibonacci term for positive n
<syntaxhighlight lang="supercollider">
<lang SuperCollider>
f = { |n| if(n < 2) { n } { f.(n-1) + f.(n-2) } };
(0..20).collect(f)
</syntaxhighlight>
</lang>
 
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) } };
(-20..20).collect(f)
</syntaxhighlight>
</lang>
 
===Analytic===
<syntaxhighlight lang="supercollider">(
<lang SuperCollider>(
f = { |n|
var sqrt5 = sqrt(5);
Line 12,154 ⟶ 13,895:
};
(0..20).collect(f)
)</langsyntaxhighlight>
 
===Iterative===
<syntaxhighlight lang="supercollider">
<lang SuperCollider>
f = { |n| var a = [1, 1]; n.do { a = a.addFirst(a[0] + a[1]) }; a.reverse };
f.(18)
</syntaxhighlight>
</lang>
 
=={{header|Swift}}==
===Analytic===
<langsyntaxhighlight Swiftlang="swift">import Cocoa
 
func fibonacci(n: Int) -> Int {
Line 12,175 ⟶ 13,916:
for i in 1...30 {
println(fibonacci(i))
}</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight Swiftlang="swift">func fibonacci(n: Int) -> Int {
if n < 2 {
return n
Line 12,188 ⟶ 13,929:
}
return fib
}</langsyntaxhighlight>
Sequence:
<langsyntaxhighlight lang="swift">func fibonacci() -> SequenceOf<UInt> {
return SequenceOf {() -> GeneratorOf<UInt> in
var window: (UInt, UInt, UInt) = (0, 0, 1)
Line 12,198 ⟶ 13,939:
}
}
}</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight Swiftlang="swift">func fibonacci(n: Int) -> Int {
if n < 2 {
return n
Line 12,209 ⟶ 13,950:
}
 
println(fibonacci(30))</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="tailspin">
templates nthFibonacci
when <=0|=1> do $ !
otherwise ($ - 1 -> #) + ($ - 2 -> #) !
end nthFibonacci
</syntaxhighlight>
</lang>
 
===Iterative, mutable state===
We could use the templates internal mutable state, still only positive N.
<langsyntaxhighlight lang="tailspin">
templates nthFibonacci
@: {n0: 0"1", n1: 1"1"};
Line 12,229 ⟶ 13,970:
$@.n0!
end nthFibonacci
</syntaxhighlight>
</lang>
To handle negatives, we can keep track of the sign and send it to the matchers.
<langsyntaxhighlight lang="tailspin">
templates nthFibonacci
@: {n0: 0"1", n1: 1"1"};
Line 12,242 ⟶ 13,983:
@: {n0: $@.n1 - $@.n0, n1: $@.n0};
end nthFibonacci
</syntaxhighlight>
</lang>
 
===State machine===
Instead of mutating state, we could just recurse internally on a state structure.
<langsyntaxhighlight lang="tailspin">
templates nthFibonacci
{ N: ($)"1", n0: 0"1", n1: 1"1" } -> #
Line 12,263 ⟶ 14,004:
-6 -> nthFibonacci -> '$;
' -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 12,276 ⟶ 14,017:
====Iterative====
{{trans|Perl}}
<langsyntaxhighlight lang="tcl">proc fibiter n {
if {$n < 2} {return $n}
set prev 1
Line 12,284 ⟶ 14,025:
}
return $fib
}</langsyntaxhighlight>
====Recursive====
<langsyntaxhighlight lang="tcl">proc fib {n} {
if {$n < 2} then {expr {$n}} else {expr {[fib [expr {$n-1}]]+[fib [expr {$n-2}]]} }
}</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="tcl">proc tcl::mathfunc::fib {n} {
if { $n < 2 } {
return $n
Line 12,301 ⟶ 14,042:
# or, more tersely
 
proc tcl::mathfunc::fib {n} {expr {$n<2 ? $n : fib($n-1) + fib($n-2)}}</langsyntaxhighlight>
 
E.g.:
 
<langsyntaxhighlight lang="tcl">expr {fib(7)} ;# ==> 13
 
namespace path tcl::mathfunc #; or, interp alias {} fib {} tcl::mathfunc::fib
fib 7 ;# ==> 13</langsyntaxhighlight>
 
====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.
<langsyntaxhighlight lang="tcl">proc fib-tailrec {n} {
proc fib:inner {a b n} {
if {$n < 1} {
Line 12,323 ⟶ 14,064:
}
return [fib:inner 0 1 $n]
}</langsyntaxhighlight>
% fib-tailrec 100
354224848179261915075
Line 12,329 ⟶ 14,070:
===Handling Negative Numbers===
====Iterative====
<langsyntaxhighlight lang="tcl">proc fibiter n {
if {$n < 0} {
set n [expr {abs($n)}]
Line 12,345 ⟶ 14,086:
}
fibiter -5 ;# ==> 5
fibiter -6 ;# ==> -8</langsyntaxhighlight>
====Recursive====
<langsyntaxhighlight 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(-6)} ;# ==> -8</langsyntaxhighlight>
===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>
{{works with|Tcl|8.5}}
<langsyntaxhighlight lang="tcl">proc fib n {expr {round((.5 + .5*sqrt(5)) ** $n / sqrt(5))}}</langsyntaxhighlight>
 
=={{header|Tern}}==
 
===Recursive===
<langsyntaxhighlight lang="tern">func fib(n) {
if (n < 2) {
return 1;
}
return fib(n - 1) + fib(n - 2);
}</langsyntaxhighlight>
 
===Coroutine===
<langsyntaxhighlight lang="tern">func fib(n) {
let a = 1;
let b = 2;
Line 12,374 ⟶ 14,115:
(a, b) = (b, a + b);
}
}</langsyntaxhighlight>
 
=={{header|TI-83 BASICSR-56}}==
Sequence table:
<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 </lang>
 
{| class="wikitable"
Iterative:
|+ Texas Instruments SR-56 Program Listing for "Fibonacci Sequence"
<lang ti83b>{0,1
|-
While 1
! Display !! Key !! Display !! Key !! Display !! Key !! Display !! Key
Disp Ans(1
|-
{Ans(2),sum(Ans
| 00 33 || STO || 25 || || 50 || || 75 ||
End</lang>
|-
| 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.
Binet's formula:
<lang ti83b>Prompt N
.5(1+√(5 //golden ratio
(Ans^N–(-Ans)^-N)/√(5</lang>
 
{| class="wikitable"
=={{header|TI-89 BASIC}}==
|+ Register allocation
===Recursive===
|-
Optimized implementation (too slow to be usable for ''n'' higher than about 12).
| 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:
<lang ti89b>fib(n)
<syntaxhighlight lang="text">
when(n<2, n, fib(n-1) + fib(n-2))</lang>
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:'''
===Iterative===
Unoptimized implementation (I think the for loop can be eliminated, but I'm not sure).
 
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.
<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</lang>
 
{{in}}
=={{header|Tiny BASIC}}==
<pre>1 RST R/S</pre>
<lang Tiny 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
</lang>
 
{{out}}
=={{header|True BASIC}}==
<pre>1</pre>
<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
 
{{in}}
PRINT fibonacci(0) ! 0
<pre>2 RST R/S</pre>
PRINT fibonacci(13) ! 233
 
PRINT fibonacci(-42) !-267914296
{{out}}
PRINT fibonacci(47) ! 2971215073
END<pre>1</langpre>
 
{{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">
<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]
INTEGER PROC FNMathGetSeriesFibonacciI( INTEGER nI )
Line 12,521 ⟶ 14,333:
UNTIL FALSE
END
</syntaxhighlight>
 
</lang>
 
=={{header|Turing}}==
<langsyntaxhighlight lang="turing">% Recursive
function fibb (n: int) : int
if n < 2 then
Line 12,547 ⟶ 14,358:
for i : 0 .. 10
put fibb (i) : 4, ifibb (i) : 4
end for</langsyntaxhighlight>
 
Output:<pre> 0 0
Line 12,562 ⟶ 14,373:
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
ASK "What fibionacci number do you want?": searchfib=""
Line 12,577 ⟶ 14,388:
PRINT "fibionacci number ",n,"=",fib
ENDLOOP
</syntaxhighlight>
</lang>
Output:
<pre>
Line 12,593 ⟶ 14,404:
fibionacci 46=1836311903
</pre>
 
=={{header|Uiua}}==
{{works with|Uiua|0.10.0-dev.1}}
Simple recursive example with memoisation.
<syntaxhighlight lang="Uiua">
F ← |1 memo⟨+⊃(F-1)(F-2)|∘⟩<2.
F ⇡20
</syntaxhighlight>
 
=={{header|UNIX Shell}}==
{{works with|bash|3}}
<langsyntaxhighlight lang="bash">#!/bin/bash
 
a=0
Line 12,607 ⟶ 14,426:
echo "F($n): $a"
b=$(($a - $b))
done</langsyntaxhighlight>
 
Recursive:
{{works with|bash|3}}
 
<langsyntaxhighlight lang="bash">fib() {
local n=$1
[ $n -lt 2 ] && echo -n $n || echo -n $(( $( fib $(( n - 1 )) ) + $( fib $(( n - 2 )) ) ))
}</langsyntaxhighlight>
 
=={{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.}}
 
<langsyntaxhighlight 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</langsyntaxhighlight>
 
=={{header|Ursa}}==
{{trans|Python}}
===Iterative===
<langsyntaxhighlight lang="ursa">def fibIter (int n)
if (< n 2)
return n
Line 12,639 ⟶ 14,458:
end for
return fib
end</langsyntaxhighlight>
 
=={{header|Ursala}}==
All three methods are shown here, and all have unlimited precision.
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
Line 12,656 ⟶ 14,475:
(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+-+-</langsyntaxhighlight>
The analytical method uses arbitrary precision floating point
arithmetic from the mpfr library and then converts the result to
Line 12,662 ⟶ 14,481:
always chosen based on the argument. This test program computes the first
twenty Fibonacci numbers by all three methods.
<langsyntaxhighlight Ursalalang="ursala">#cast %nLL
 
examples = <.iterative_fib,recursive_fib,analytical_fib>* iota20</langsyntaxhighlight>
output:
<pre>
Line 12,692 ⟶ 14,511:
Generate n'th fib by using binary recursion
 
<langsyntaxhighlight lang="v">[fib
[small?] []
[pred dup pred]
[+]
binrec].</langsyntaxhighlight>
 
=={{header|Vala}}==
Line 12,702 ⟶ 14,521:
===Recursive===
Using int, but could easily replace with double, long, ulong, etc.
<langsyntaxhighlight lang="vala">
int fibRec(int n){
if (n < 2)
Line 12,709 ⟶ 14,528:
return fibRec(n - 1) + fibRec(n - 2);
}
</syntaxhighlight>
</lang>
 
===Iterative===
Using int, but could easily replace with double, long, ulong, etc.
<langsyntaxhighlight lang="vala">
int fibIter(int n){
if (n < 2)
Line 12,730 ⟶ 14,549:
return cur;
}
</syntaxhighlight>
</lang>
 
=={{header|VAX Assembly}}==
<langsyntaxhighlight VAXlang="vax Assemblyassembly"> 0000 0000 1 .entry main,0
7E 7CFD 0002 2 clro -(sp) ;result buffer
5E DD 0005 3 pushl sp ;pointer to buffer
Line 12,767 ⟶ 14,586:
1836311903
$
</syntaxhighlight>
</lang>
 
=={{header|VBA}}==
Like Visual Basic .NET, but with keyword "Public" and type Variant (subtype Currency) instead of Decimal:
<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 </lang>
With Currency type, maximum value is fibo(73).
 
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>
 
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:====
<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}}==
===Iterative===
 
Calculate fibonacci(#1). Negative values return 0.
<langsyntaxhighlight lang="vedit">:FIBONACCI:
#11 = 0
#12 = 1
Line 12,872 ⟶ 14,599:
#12 = #10
}
Return(#11)</langsyntaxhighlight>
 
===Unlimited precision===
<langsyntaxhighlight lang="vedit">// Fibonacci, unlimited precision.
// input: #1 = n
// return: fibonacci(n) in text register 10
Line 12,929 ⟶ 14,656:
}
Buf_Quit(OK)
return</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight 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</langsyntaxhighlight>
 
{{out}}
<pre>fibonacci(1000) = 43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875</pre>
 
=={{header|VisualV Basic(Vlang)}}==
Update V (Vlang) to version 0.2.2
{{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.
<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</lang>
{{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).
<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</lang>
===Recursive===
{{works with|Visual Basic .NET|9.0+}}
<lang vbnet>Function Seq(ByVal Term As Integer)
If Term < 2 Then Return Term
Return Seq(Term - 1) + Seq(Term - 2)
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
 
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</lang>
 
===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''.]
<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</lang>
{{out}}
<pre>120.374 ms to calculate the 2,000,000th Fibonacci number, number of digits is 417975
partial: 85312949175076415430516606545038251...91799493108960825129188777803453125</pre>
 
=={{header|Vlang}}==
Update Vlang to version 0.2.2
===Iterative===
<langsyntaxhighlight lang="go">fn fib_iter(n int) int {
if n < 2 {
return n
Line 13,098 ⟶ 14,687:
println('fibonacci(${val:2d}) = ${fib_iter(val):3d}')
}
}</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="go">fn fib_rec(n int) int {
if n < 2 {
return n
Line 13,113 ⟶ 14,702:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>fibonacci( 0) = 0
Line 13,131 ⟶ 14,720:
 
===Recursive, all at once===
<langsyntaxhighlight lang="python">def (fib n)
if (n < 2)
n
(+ (fib n-1) (fib n-2))</langsyntaxhighlight>
 
===Recursive, using cases===
<langsyntaxhighlight lang="python">def (fib n)
(+ (fib n-1) (fib n-2))
 
def (fib n) :case (n < 2)
n</langsyntaxhighlight>
 
===Recursive, using memoization===
<langsyntaxhighlight lang="python">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</langsyntaxhighlight>
 
=={{header|WDTE}}==
 
===Memoized Recursive===
<langsyntaxhighlight WDTElang="wdte">let memo fib n => n { > 1 => + (fib (- n 1)) (fib (- n 2)) };</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight WDTElang="wdte">let s => import 'stream';
let a => import 'arrays';
 
Line 13,166 ⟶ 14,755:
-> a.at 1
;
);</langsyntaxhighlight>
 
=={{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}}==
Line 13,221 ⟶ 14,810:
===Iterative===
This program generates Fibonacci numbers until it is [http://ideone.com/VBDLzk forced to terminate].
<syntaxhighlight lang="whitespace">
<lang Whitespace>
 
Line 13,233 ⟶ 14,822:
</langsyntaxhighlight>
 
It was generated from the following pseudo-Assembly.
<langsyntaxhighlight lang="asm">push 0
push 1
 
Line 13,247 ⟶ 14,836:
copy 1
add
jump 0</langsyntaxhighlight>
{{out}}
<pre>$ wspace fib.ws | head -n 6
Line 13,260 ⟶ 14,849:
 
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 13,288 ⟶ 14,877:
 
</langsyntaxhighlight>
<langsyntaxhighlight lang="asm">; Read n.
push 0
dup
Line 13,317 ⟶ 14,906:
add ; Leave the sum on the stack.
1:
ret</langsyntaxhighlight>
 
{{out}}
Line 13,325 ⟶ 14,914:
=={{header|Wrapl}}==
===Generator===
<langsyntaxhighlight lang="wrapl">DEF fib() (
VAR seq <- [0, 1]; EVERY SUSP seq:values;
REP SUSP seq:put(seq:pop + seq[1])[-1];
);</langsyntaxhighlight>
To get the 17th number:
<syntaxhighlight lang ="wrapl">16 SKIP fib();</langsyntaxhighlight>
To get the list of all 17 numbers:
<syntaxhighlight lang ="wrapl">ALL 17 OF fib();</langsyntaxhighlight>
===Iterator===
Using type match signature to ensure integer argument:
<langsyntaxhighlight lang="wrapl">TO fib(n @ Integer.T) (
VAR seq <- [0, 1];
EVERY 3:to(n) DO seq:put(seq:pop + seq[1]);
RET seq[-1];
);</langsyntaxhighlight>
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">// iterative (quick)
var fibItr = Fn.new { |n|
if (n < 2) return n
Line 13,363 ⟶ 14,952:
 
System.print("Iterative: %(fibItr.call(36))")
System.print("Recursive: %(fibRec.call(36))")</langsyntaxhighlight>
 
{{out}}
Line 13,373 ⟶ 14,962:
=={{header|x86 Assembly}}==
{{Works with|MASM}}
<langsyntaxhighlight lang="asm">TITLE i hate visual studio 4 (Fibs.asm)
; __ __/--------\
; >__ \ / | |\
Line 13,423 ⟶ 15,012:
main ENDP
 
END main</langsyntaxhighlight>
 
=={{header|xEec}}==
This will display the first 93 numbers of the sequence.
<syntaxhighlight lang="xeec">
<lang xEec>
h#1 h#1 h#1 o#
h#10 o$ p
Line 13,435 ⟶ 15,024:
t
jnf
</syntaxhighlight>
</lang>
 
=={{header|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.
<langsyntaxhighlight lang="lisp">(DEFUN FIBONACCI (N)
(FLOOR (+ (/ (EXPT (/ (+ (SQRT 5) 1) 2) N) (SQRT 5)) 0.5)))</langsyntaxhighlight>
To test it, we'll define a <tt>RANGE</tt> function and ask for the first 50 numbers in the sequence:
<langsyntaxhighlight lang="lisp">(DEFUN RANGE (X Y)
(IF (<= X Y)
(CONS X (RANGE (+ X 1) Y))))
 
(PRINT (MAPCAR FIBONACCI (RANGE 1 50)))</langsyntaxhighlight>
{{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>
Line 13,453 ⟶ 15,042:
===Tail recursive===
Alternatively, this approach is reasonably efficient:
<langsyntaxhighlight lang="lisp">(defun fibonacci (x)
(defun fib (a b n)
(if (= n 2)
Line 13,460 ⟶ 15,049:
(if (< x 2)
x
(fib 1 1 x) ) )</langsyntaxhighlight>
 
=={{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.
<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</lang>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">func Fib1(N); \Return Nth Fibonacci number using iteration
int N;
int Fn, F0, F1;
Line 13,502 ⟶ 15,074:
for N:= 0 to 20 do [IntOut(0, Fib2(N)); ChOut(0, ^ )];
CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 13,511 ⟶ 15,083:
 
=={{header|XQuery}}==
<langsyntaxhighlight lang="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)
};</langsyntaxhighlight>
 
=={{header|Z80 Assembly}}==
<syntaxhighlight lang="z80">; 8 bit version
; IN : a = n (n <= 13, otherwise overflows)
; OUT: a = FIB(n)
 
fib8: cp 2
=={{header|Yabasic}}==
ret c ; if n < 2 then done
<lang yabasic>sub fibonacci (n)
 
n1 = 0
ld b,a
n2 = 1
dec b ; b = forn k =- 1 to abs(n)
ld c,0 ; F0
sum = n1 + n2
ld a,1 ; F1
n1 = n2
 
n2 = sum
f8_l: ld d,a
next k
add a,c
if n < 0 then
ld c,d
return n1 * ((-1) ^ ((-n) + 1))
djnz f8_l
else
 
return n1
ret
end if
</syntaxhighlight>
end sub</lang>
 
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}}==
A slight tweak to the task; creates a function that continuously generates fib numbers
<langsyntaxhighlight lang="zkl">var fibShift=fcn(ab){ab.append(ab.sum()).pop(0)}.fp(L(0,1));</langsyntaxhighlight>
<pre>
zkl: do(15){ fibShift().print(",") }
Line 13,544 ⟶ 15,170:
610,987,1597,2584,4181,
</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]]
416

edits