Recursive and non-recursive implementation of Fibonacci sequence in Java interview __java

Source: Internet
Author: User

Question: Find the nth number in the Fibonacci sequence.

The so-called Fibonacci sequence refers to: The first 2 numbers are 0 and 1. The number of i-1 and the number of i-2.

The first 10 numbers of the Fibonacci series are:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...

Answer:

(i) Recursive implementation:

Class Solution {
    /**
     * @param n:an integer
     * @return an integer f (n) */public
    int Fibonacci (int n) {
       if (n==1) {return
           0;
       } else if (n==2) {return
           1;
       }
       else {return
           Fibonacci (n-1) +fibonacci (n-2);
}}} Total time consuming: 4634 ms


(ii) Non-recursive implementation

Class Solution {
    /**
     * @param n:an integer
     * @return an integer f (n) */public
    int Fibonacci (int n) {
        int before=0,behind=0;
        int result=0;
        for (int i=0;i<n;i++) {
            if (i==0) {
                result=0;
                before=0;
                behind=0;
            }
            else if (i==1) {
                result=1;
                before=0;
                Behind=result;
            } else{
                Result=before+behind;
                Before=behind;
                Behind=result
                
            }
        }
        return result;
    }
Total time consuming: 1389 ms

We see that the method of non recursion is obviously optimized and the time is reduced.

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.