phpeveryday.com

The best tutorial of php, php framework, php strategies, object oriented oriented,


PHP - Number: Generating Fibonacci Numbers

Tag: number, fibonacci, PEAR   Category: PHP Basic
post: 16 Mar 2008 read: 60


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";
?>



| Give Your Opinion | Recommend
Share and Bookmark to: These icons link to social bookmarking sites where readers can share and discover new web pages.
digg del.icio.us technorati Ma.gnolia BlinkList

Recommended articles by other readers:
Web Services: How PHP Kiss VB.NET? (Part 1)
Chart: How to Build Cool Animation Real Time Chart
Joomla: Fast Road to Understand Component Programming
Email: Send Attachement Mail
mod_rewrite - Part 1: create your "fantasy" URL

What do You Think?
Your Name *:
Email *:
(Will not be published)
Website/URL:
Your Comment *:
* Required


615
posting