Fibonacci sequence without recursion C++

Title description

Everyone knows the Fibonacci sequence. Now it is required to input an integer n. Please output the nth term of the Fibonacci sequence (starting from 0, the 0th term is 0).

n<=39

 I used the recursive method at first, and then overtime, and then used the following solution:

class Solution {
public:
    int Fibonacci(int n) {
       if(n==0)
           return 0;
        if(n==1)
            return 1;
        int a=0,b=1,c=0;
        for(int i=2;i<=n;i++){
            c=a+b;
            a=b;
            b=c;
        }
        return c;
    }
};

Recursion really looks cool, but it loses to the conventional solution. The conventional solution is best understood and solves the problem. Why not do it.

c=a+b;

a=b;

b=c;

This structure is the clearest and fully reflects the rules of the Fibonacci sequence:

When n=2, the next item is 0+1, then output the result 2, and the number sequence is 0, 1, 2; this needs to be done once in the for loop;

When n=3, the next item is 1+2, and then output the result 3, the number sequence is 0, 1, 2, 3; this needs to be done twice in the for loop;

When n=4, the next item is 2+3, and then output the result 5, the number sequence is 0, 1, 2, 3, 5; this needs to be performed 3 times in the for loop;

n starts at 2, so i must start at 2 to be satisfied.

Guess you like

Origin blog.csdn.net/sinat_39416814/article/details/105117656