## Posted By

bcmoney on 06/07/12

# Fibonacci series (several different algorithms)

/ Published in: PHP

Planning to add proper PHPunit and PHPlogger code examples and blog about it at http://bcmoney-mobiletv.com/blog/

`<?php /************************************************* * Fibonacci Sequence *   The original predictive algorithm. This is a  *   compilation of several algorithms for computing *   it in PHP5+. *   More info on Fibonacci number:  *   http://en.wikipedia.org/wiki/Fibonacci_number * @author bcmoney  * @author David Stockton *************************************************/ /** * Recursive *   http://www.codewalkers.com/c/a/Miscellaneous/Recursion-in-PHP/2/#fkj8Lr7BcSAZCQQv.99 */function fibonacci_recursive (\$n) {  if (\$n == 1 || \$n == 2) {    return 1;  }  else {    return fibonacci_recursive(\$n - 1)+fibonacci_recursive(\$n - 2);  }}  /**  * Iterative *   http://www.codewalkers.com/c/a/Miscellaneous/Recursion-in-PHP/3/ * @author David Stockton  */function fibonacci_iterative(\$num, \$show_series="no") {  \$retval = "";  if (\$num == 1 ) {    return 1;  }  \$num1=1;  \$num2=0;  \$retval = "1";   for (\$i = 1; \$i &lt; \$num; \$i++) {    \$fib = \$num2 + \$num1;    \$num2 = \$num1;    \$num1=\$fib;    if (\$show_series == 'yes') {        \$retval .= ", ".\$fib;    }  }  if (\$show_series == 'yes') {    return \$retval;  } else {    return \$fib;  }}  /*************************************************//* calculate, log and time each function *//*************************************************/  \$time = microtime();  \$time = explode(" ", \$time);  \$time1 = \$time + \$time[0];echo fibonacci_recursive(50, "yes");  \$time = microtime();  \$time = explode(" ", \$time);  \$time2 = \$time[1] + \$time[0];echo fibonacci_iterative(50, "yes");  \$time = microtime();  \$time = explode(" ", \$time);  \$time3 = \$time[2] + \$time[1] + \$time[0];  \$totaltime = (\$time3 - \$time2 - \$time1);   echo "Recursive: ".\$time1."\n<br/>\n";  echo "Iterative: ".\$time2."\n<br/>\n";  echo "Total runtime: ".\$totaltime."\n<br/>\n";?>`