PHP - Number: Generating Fibonacci Numbers


PHP Number Tips - Part 20: If you want to generate a series of Fibonacci numbers or find out if a particular number belongs to the Fibonacci sequence, you have to define the first two numbers and then use a loop to calculate the rest such as:
<?php
// generate the first N Fibonacci numbers
function generateFibonacciNumbers($size) {
  // define array to hold Fibonacci numbers
  $fibonacciArray = array();
  
  $fibonacciArray[0] = 0; // by definition
  $fibonacciArray[1] = 1; // by definition
  
  // generate numbers
  for ($x=2; $x<=$size; $x++) {
    $fibonacciArray[$x] = $fibonacciArray[$x-2] + ↵
$fibonacciArray[$x-1];
  }
  
// return array
return $fibonacciArray;
}

// list the first 20 Fibonacci numbers
// result: "0 1 1 2 3 5 8...2584 4181 6765"
echo implode(" ", generateFibonacciNumbers(20));
?>

In the Fibonacci number sequence, every number is formed from the sum of the previous two numbers. The first few numbers in this sequence are 1, 1, 2, 3, 5, and 8. You can save yourself some time with PEAR's Math_Fibonacci class and this class comes with a series( ) method that generates the first n numbers of the Fibonacci sequence and a term( ) method. Both methods return an object which must be decoded with the toString( ) method. Here is the listing:

<?php
// include Math_Fibonacci class
include "Math/Fibonacci.php";

// list the first 20 Fibonacci numbers
// result: "0 1 1 2 3 5 8...4181 6765"
$series = Math_Fibonacci::series(20);
foreach ($series as $k=>$v) {
  print $v->toString() . " ";
}

// calculate the 5th Fibonacci number
// result: 5
$fib5 = Math_Fibonacci::term(5);
print $fib5->toString();
?>

Beside that, you can also test if a particular number belongs to the Fibonacci sequence with the isFibonacci( ) class method. Here is the listing illustrates:

<?php
// include Math_Fibonacci class
include "Math/Fibonacci.php";

// define number
$num = 21;

// check if number belongs to the Fibonacci sequence
// result: "Is a Fibonacci number"
echo Math_Fibonacci::isFibonacci(new Math_Integer($num)) ↵
? "Is a Fibonacci number" : "Is not a Fibonacci number";
?>



Bookmark and Share Tag: number, fibonacci, PEAR Category: PHP Basic Post : March 16th 2008 Read: 8,901

advertisements


blog comments powered by Disqus