Posted By

bcmoney on 06/07/12


Tagged

fibonacci Algorithms


Versions (?)

Fibonacci series (several different algorithms)


 / Published in: PHP
 

URL: http://bcmoney-mobiletv.com/blog/

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

  1. <?php
  2.  
  3. /*************************************************
  4.  * Fibonacci Sequence
  5.  * The original predictive algorithm. This is a
  6.  * compilation of several algorithms for computing
  7.  * it in PHP5+.
  8.  * More info on Fibonacci number:
  9.  * http://en.wikipedia.org/wiki/Fibonacci_number
  10.  * @author bcmoney
  11.  * @author David Stockton
  12.  *************************************************/
  13.  
  14. /**
  15.  * Recursive
  16.  * http://www.codewalkers.com/c/a/Miscellaneous/Recursion-in-PHP/2/#fkj8Lr7BcSAZCQQv.99
  17.  */
  18. function fibonacci_recursive ($n) {
  19. if ($n == 1 || $n == 2) {
  20. return 1;
  21. }
  22. else {
  23. return fibonacci_recursive($n - 1)+fibonacci_recursive($n - 2);
  24. }
  25. }
  26.  
  27.  
  28. /**
  29.  * Iterative
  30.  * http://www.codewalkers.com/c/a/Miscellaneous/Recursion-in-PHP/3/
  31.  * @author David Stockton
  32.  */
  33. function fibonacci_iterative($num, $show_series="no") {
  34. $retval = "";
  35. if ($num == 1 ) {
  36. return 1;
  37. }
  38. $num1=1;
  39. $num2=0;
  40. $retval = "1";
  41.  
  42. for ($i = 1; $i &lt; $num; $i++) {
  43. $fib = $num2 + $num1;
  44. $num2 = $num1;
  45. $num1=$fib;
  46. if ($show_series == 'yes') {
  47. $retval .= ", ".$fib;
  48. }
  49. }
  50. if ($show_series == 'yes') {
  51. return $retval;
  52. } else {
  53. return $fib;
  54. }
  55. }
  56.  
  57.  
  58. /*************************************************/
  59. /* calculate, log and time each function */
  60. /*************************************************/
  61. $time = microtime();
  62. $time = explode(" ", $time);
  63. $time1 = $time + $time[0];
  64. echo fibonacci_recursive(50, "yes");
  65. $time = microtime();
  66. $time = explode(" ", $time);
  67. $time2 = $time[1] + $time[0];
  68. echo fibonacci_iterative(50, "yes");
  69. $time = microtime();
  70. $time = explode(" ", $time);
  71. $time3 = $time[2] + $time[1] + $time[0];
  72. $totaltime = ($time3 - $time2 - $time1);
  73.  
  74. echo "Recursive: ".$time1."\n<br/>\n";
  75. echo "Iterative: ".$time2."\n<br/>\n";
  76. echo "Total runtime: ".$totaltime."\n<br/>\n";
  77. ?>

Report this snippet  

You need to login to post a comment.