# Fibonacci numbers (Prolog)

From LiteratePrograms

**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

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.

## [edit] Implementation

### [edit] 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.

### [edit] 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).

Download code |