Skip to content

Instantly share code, notes, and snippets.

@okiwan
Last active August 29, 2015 14:02
Show Gist options
  • Save okiwan/7914136ba8ac017ec499 to your computer and use it in GitHub Desktop.
Save okiwan/7914136ba8ac017ec499 to your computer and use it in GitHub Desktop.
Fibonacci demo
#!/usr/bin/php
<?php
define('GOAL', 30);
function fibonacciV1($n = 0) {
if(!$n) : return 0;
elseif ($n < 3) : return 1;
else : return fibonacciV1($n-1) + fibonacciV1($n-2);.
endif;
return 1;
}
function fibonacciV2($n = 0) {
$current = 3;
$fibTemp = array(0, 1, 1);
if($n < 3): return $fibTemp[$n]; endif;
while($current <= $n) {
$fibTemp[$current] = $fibTemp[$current-1] + $fibTemp[$current-2];
$current++;
}
return $fibTemp[$current-1];
}
# Main routine
print ">> Fibonacci DEMO\n";
$start = microtime(true);
print "V1 | F(" . GOAL . ") = " . fibonacciV1(GOAL) . "\n";
$end = microtime(true);
print "V1 | " . ($end - $start) . " seconds\n";
$start = microtime(true);
print "V2 | F(" . GOAL . ") = " . fibonacciV2(GOAL) . "\n";
$end = microtime(true);
print "V2 | " . ($end - $start) . " seconds\n";
print ">> Have a nice day!\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment