# Difference between revisions of "Fibonacci number"

From Free Pascal wiki

m |
|||

Line 51: | Line 51: | ||

== See also == | == See also == | ||

− | * [http://www.freepascal.org/prog/progsu151.html | + | * [http://www.freepascal.org/docs-html/prog/progsu151.html Some assembly routine which uses the C calling convention that calculates the nth Fibonacci number] |

* [[Solution_3| Tao Yue Solution to Fibonacci Sequence Problem]] | * [[Solution_3| Tao Yue Solution to Fibonacci Sequence Problem]] | ||

[[Category:Mathematics]] | [[Category:Mathematics]] |

## Revision as of 09:41, 23 November 2016

│
**Deutsch (de)** │
**English (en)** │
**suomi (fi)** │
**français (fr)** │
**русский (ru)** │

# Fibonacci number

The Fibonacci Sequence is the series of numbers:

0, 1, 1, 2, 3, 5, 8, 13, 21, ...

The idea is to add the two last numbers, and thus get the next value.

## Recursive way

```
function FibonacciNumber( n : integer ): integer;
begin
if n > 1 then result := ( FibonacciNumber( n - 1 ) + FibonacciNumber( n - 2 ) )
else
if n = 0 then result := 0
else result := 1;
end;
```

## Iterative way

This one is preferable.

```
function Fibonacci(n: Integer): Integer;
var
i,u,v,w: Integer;
begin
if n <= 0 then
exit(0);
if n = 1 then
exit(1);
u := 0;
v := 1;
for i := 2 to n do
begin
w := u + v;
u := v;
v := w;
end;
Result := v;
End;
```