PHP two ways to achieve the Fibonacci number

Source: Internet
Author: User
Tags explode

  1. 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);        }    }

  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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.