- Use recursive methods.
// using recursion to find Fibonacci numbers Public function fb ($n) { // if$n <=2) { return 1; } Else { return fb ($n-1) + FB ($n-2); } }
- Use a recursive approach.
//using recursion to find the Fibonacci number Public functionFB2 ($n){// if($n<=2){ return1; } $t 1= 1;$t 2= 1; for($i= 3;$i<$n;$i++){ $temp=$t 1; $t 1=$t 2; $t 2=$temp+$t 2; } return $t 1+$t 2; }
Finally, perform a performance analysis.
Obviously predictable, recursive methods, each layer, will be recursive down two times. About O (2 of the n-th square) and the recursive method is O (n), the actual code is as follows.
/** Performance tuning. */functionBench_profile ($starttime,$flag= ' '){ $endtime=Explode(‘ ‘,Microtime()); $thistime=$endtime[0]+$endtime[1]-($starttime[0]+$starttime[1]); $thistime=round($thistime, 3); return $flag." -bench: ".$thistime. "SEC";}//use recursive algorithms. Ini_set("Max_execution_time", 3600); $s=Explode(‘ ‘,Microtime()); EchoBench_profile ($s)." <br/> "; EchoFB (35);//use recursion time-consuming 40.925 sec each to the previous number about twice times slower EchoBench_profile ($s)." <br/> "; $s=Explode(‘ ‘,Microtime()); EchoBench_profile ($s)." <br/> "; EchoFB2 (35);//The use of recursive time is extremely short. EchoBench_profile ($s)." <br/> ";
Summary: Code performance is a good key that distinguishes programmers from getting started and not getting started.
Using a recursive algorithm, go to 100thFibonacci numberWhen the machine does not move, and the use of recursive algorithm, almost no time.
PHP two ways to achieve the Fibonacci number