Saturday, July 12, 2008

Fibonacci numbers

The Fibonacci numbers have many applications in computer programming. Today we're going to write a function that returns individual numbers from the Fibonacci sequence.


ASP

  1. function fib(x)
  2.     dim fibArray()
  3.     redim fibArray(x)
  4.     fibArray(0) = 0
  5.     fibArray(1) = 1
  6.     for i = 2 to x
  7.         fibArray(i) = fibArray(i - 1) + fibArray(i - 2)
  8.     next
  9.     fib = fibArray(x)
  10. end function

PHP

  1. function fib($x)
  2. {
  3.     $fibArray[0] = 0;
  4.     $fibArray[1] = 1;
  5.     for($i = 2; $i <= $x; $i++)
  6.     {
  7.         $fibArray[$i] = $fibArray[$i - 1] + $fibArray[$i - 2];
  8.     }
  9.     return $fibArray[$x];
  10. }

So, for example, fib(8) will return 21, because the Fibonacci sequence is 1, 1, 2, 3, 5, 8, 13, 21, 34, 55...


No comments: