Difference between revisions of "Fibonacci number"

From Free Pascal wiki
Line 14: Line 14:
 
function FibonacciNumber( n : integer ): integer;
 
function FibonacciNumber( n : integer ): integer;
 
begin
 
begin
   if n = 0  then result := 0
+
   if n > 1 then result := ( FibonacciNumber( n - 1 ) + FibonacciNumber( n - 2 ) )
  else
+
    else
    if n = 1 then result := 1
+
      if n = 0 then result := 0
      else result := ( FibonacciNumber( n - 1 ) + FibonacciNumber( n - 2) );
+
        else result := 1;
 
end;  
 
end;  
  

Revision as of 09:33, 16 November 2014

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;


See also