# Fibonacci numbers (Prolog)

Other implementations: bc | C | C Plus Plus templates | dc | E | Erlang | FORTRAN | Haskell | Icon | Java | JavaScript | Lisp | Lua | occam | Oz | PIR | Prolog | Python | Sed | sh | sh, iterative | T-SQL | Visual Basic .NET

The Fibonacci numbers are the integer sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, ..., in which each item is formed by adding the previous two. The sequence can be defined recursively by

$F(n) = \begin{cases} 0 & n = 0 \\ 1 & n = 1 \\ F(n-1)+F(n-2) & n > 1 \\ \end{cases} .$

Fibonacci number programs that implement this definition directly are often used as introductory examples of recursion. However, many other algorithms for calculating (or making use of) Fibonacci numbers also exist.

##  Implementation

###  Naive

<<fibonacci_naive.pl>>=
fib(0, 0).
fib(1, 1).
fib(N, NF) :-
A is N - 1, B is N - 2,
fib(A, AF), fib(B, BF),
NF is AF + BF.


###  Tail recursive

<<fibonacci.pl>>=
fib(0, A, _, A).
fib(N, A, B, F) :- N1 is N - 1, Sum is A + B, fib(N1, B, Sum, F).
fib(N, F) :- fib(N, 0, 1, F).

hijacker
hijacker
hijacker
hijacker