Fibonacci Sequence algorithm

Source: Internet
Author: User

Today, we study the next Fibonacci algorithm, which realizes the value of nth in both recursive and non-recursive ways.

The code is as follows:

recursive mode:      Public Static int getfib (int  a) {        if (a==1| | a==2) {return 1;}         return getfib (a-2) +getfib (A-1);    }

non-recursive mode: Public Static intGETFIB2 (inta) {        intX=1; intY=1; if(a==1| | a==2){            return1; }         for(inti=3;i<=a;i++){            inttemp=y; Y=x+y; X=temp; }        returny; }

  print out the top n items, 5 per line  public  static  void  listfib (int   a) {StringBuilder sb  = new   StringBuilder ();  for  (int  I=1;i<=a;i++ + ""  if  (i%5 = = 0 "\ n"        
Test:      Public Static void Main (string[] args) {        listfib (+);    }
Test results:

Comparing the recursive and non-recursive algorithms, it is found that the recursive algorithm is inefficient, the main reason is that recursion involves repeated computation, can be mitigated by caching, in particular, the calculation of each record into a map, the need for direct get without recalculation, optimized after the code as follows:

  add cache-Optimized recursive algorithm:  public  static  int  getfib (int   a) {map  <integer, integer> Map = new<        /span> Hashmap<integer, Integer> ();  if  (a==1| |        a==2) {return  1;}  if   (Map.containskey (a)) { return   Map.get (a);        } Integer B  = Getfib (a-2) +getfib (A-1 return   b; }

Fibonacci Sequence algorithm

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.