The Fibonacci sequence is a sequence    Fn    of natural numbers defined recursively:

      F0 = 0 
      F1 = 1 
      Fn = Fn-1 + Fn-2, if n>1 



Task

Write a function to generate the    nth    Fibonacci number.

Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).

The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:

      Fn = Fn+2 - Fn+1, if n<0   

support for negative      n      in the solution is optional.



Related tasks

   Fibonacci n-step number sequences‎
   Leonardo numbers


References

   Wikipedia, Fibonacci number
   Wikipedia, Lucas number
   MathWorld, Fibonacci Number
   Some identities for r-Fibonacci numbers
   OEIS Fibonacci numbers
   OEIS Lucas numbers


 
MODULE Fibonacci;
IMPORT
  Out := NPCT:Console;
 
PROCEDURE Fibs(VAR r: ARRAY OF LONGREAL);
VAR
  i: LONGINT;
BEGIN
  r[0] := 1.0; r[1] := 1.0;
  FOR i := 2 TO LEN(r) - 1 DO
    r[i] := r[i - 2] + r[i - 1];
  END
END Fibs;
 
PROCEDURE FibsR(n: LONGREAL): LONGREAL;
BEGIN
  IF n < 2. THEN
    RETURN n
  ELSE
    RETURN FibsR(n - 1) + FibsR(n - 2)
  END
END FibsR;
 
PROCEDURE Show(r: ARRAY OF LONGREAL);
VAR
  i: LONGINT;
BEGIN
  Out.String("First ");Out.Int(LEN(r),0);Out.String(" Fibonacci numbers");Out.Ln;
  FOR i := 0 TO LEN(r) - 1 DO
    Out.LongRealFix(r[i],8,0)
  END;
  Out.Ln
END Show;
 
PROCEDURE Gen(s: LONGINT);
VAR
  x: POINTER TO ARRAY OF LONGREAL;
BEGIN
  NEW(x,s);
  Fibs(x^);
  Show(x^)  
END Gen;
 
PROCEDURE GenR(s: LONGINT);
VAR
  i: LONGINT;
BEGIN
  Out.String("First ");Out.Int(s,0);Out.String(" Fibonacci numbers (Recursive)");Out.Ln;
  FOR i := 1 TO s DO  
    Out.LongRealFix(FibsR(i),8,0)
  END;
  Out.Ln  
END GenR;
 
BEGIN 
  Gen(10);
  Gen(20);
  GenR(10);
  GenR(20);
END Fibonacci.
 