Fibonacci

Fibonacci sequence.

Q:Out put the n item of the sequence.

ps.the n can be very big.Mod 10007 if necessary.(n<=1,000,000).

 

S:Usually we code it by recursion(di_gui) if a question can be expressed by the recursion formular.

#include <iostream>
using namespace std;
long Fibonacci(long n){
    if(n==1||n==2) return 1;
    else{
        return (Fibonacci(n-1)+Fibonacci(n-2))%10007;
    }
}
int main(){
    int n;
    cin>>n;
    cout<<Fibonacci(n)<<endl;
}

But when n is very big,it costs a large space and a lot of time.

Why? because it does't memorize the value that caculated before.(for example,if you want the value of 8,you need number 7 and 6,number 7 need 6,5,4.....and number 6 need 5,4,3....some value have been caculated before).

So,the better solution is to recycle the value caculated before.

#include <iostream>
using namespace std;
long Fibonacci(long n){
    if(n==1||n==2) return 1;
    else{
        int F1=1,F2=1,i;
        for(i=1;i<(n+1)/2;i++){//i represents the round of circulation,we need the (n+1)/2 round;
            F1=(F1+F2)%10007;
            F2=(F1+F2)%10007;
        }
        return  n%2==0?F2:F1;//in every round ,if n is odd it's the first one;
    }
}
int main(){
    int n;
    cin>>n;
    cout<<Fibonacci(n)<<endl;
}

Input:

55

22

...

Out put:

2091

7704

 

posted @ 2020-04-24 18:32  lym1124  阅读(131)  评论(0)    收藏  举报