Algorithm Implementation/Mathematics/Fibonacci Number Program

Fibonacci is similar to a "hello world" for many functional programming languages, since it can involve paradigms like pattern matching, memoization, and bog-standard tail recursion (which is equivalent to iteration). However, iteration or tail-recursion in linear time is only the first step: more clever exponentiation runs in logarithmic time.

Although the Binet/Lucas formula is technically also exponentiation, ita use of floating-point numbers makes it less attractive than the matrix-based solution. In addition, the above discussion of complexity and indeed most of the code here assumes that both addition and multiplication are done in a single step, which is not the case for big, exponentially-growing numbers easily created by fibonacci calculation.

C
An explanation of many of the following above can be found in nayuki's post.

Matrix exponentiation, compact
A similar alternative is based on Lucas numbers.

C#
C# code is essentially the same as C with some static method specifiers.

Arithmetic version
algorithm taken from the Pascal "more efficient" version, below

Simple recursive
This version uses F# System.Numerics.BigInteger type

Forth
0 1 rot 0 ?do over + swap loop drop ;

Awesome recursive version
Or : Or :

Closed-form version
Defines arithmetic operations on a custom data type, and then uses it to run the explicit formula without going via floating point - no rounding or truncation. Calculates the ten millionth fibonacci number in a few seconds (it has roughly two million digits).

For other versions, see :
 * Haskell/Overview
 * nayuki's fast doubling again, but recursive this time

Basic Tail-Recursive Version
fibonacci?{ ??0 1   ?=0:???    (1??,+/?)? ?-1 }

Array-Oriented Version
fibonacci?{+/{?!??}(??)-?IO}

Other Versions
See Fibonacci at the Dynamic Functions Database

Linotte
Fibonacci: Principal : Rôles : n :: nombre Actions : "Entrez un nombre :" ! n ? fibo(n) ! Fibo : Rôles : * n :: nombre Actions : si n < 2 alors retourne n 	retourne fibo(n-1) + fibo(n-2)

Lexico (in Spanish)
clase Fib publicos: mensajes: Fib nop Fibonacci(deme n es una cantidad) es_funcion cantidad { 	los objetos uno, dos, tres, i, respuesta son cantidades copie 0 en uno copie 1 en dos variando i desde 1 hasta n haga: { 		copie uno en respuesta copie uno + dos en tres copie dos en uno copie tres en dos } 	retornar uno } /**********************************/ tarea { el objeto f es un Fib muestre "el 5: ", f.Fibonacci(doy 5) }

Recursive version
fib(n):= if n < 2 then n    else fib(n - 1) + fib(n - 2) $

Lucas form
fib(n):=(%phi^n-(-%phi)^-n)/sqrt(5);

Iterative version
fib(n) := block(    [i,j,k],     i : 1,     j : 0,     for k from 1 thru n do         [i,j] : [j,i + j],     return(j) )$

Exponentiation by squaring
fib(n) := block(    [i,F,A],     if n <= 0 then         return(0),     i : n - 1,     F : matrix([1,0],[0,1]),     A : matrix([0,1],[1,1]),     while i > 0 do block( if oddp(i) then F : F.A,        A : A^^2, i : quotient(i,2) ),    return(F[2,2]) )$

A bit more efficient
Note that Power is usually defined in Math, which is not included by default.

For most compilers it's possible to improve performance by using the Math.IntPower instead of the Math.Power.

Binary recursion, snippet
Runs in &Theta;(F(n)) time, which is Ω(1.6n).

Recursive version
Or :

Lucas sequence identities, recursion
As with the iterative version, this solution is also O(log n) with arbitrary precision.

Ruby
Alternate:

Logarithmic-time Version
This version squares the Fibonacci transformation, allowing calculations in log2(n) time:

UCBLogo
to fib :n output (cascade :n [?1+?2] 1 [?1] 0) end

Recursive version
to fib :n if :n<2 [output 1] output (fib :n-1)+(fib :n-2) end

Alternative recursive version
and  is optional arguments.

Iterative version
This example supports negative arguments.

Stack recursion
This example uses recursion on the stack.