Fibonacci Again

来源:互联网 发布:无印良品淘宝有真的吗 编辑:程序博客网 时间:2024/05/28 23:09

Fibonacci Again

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 40748    Accepted Submission(s): 19521


Problem Description
There are another kind of Fibonacci numbers: F(0) = 7, F(1) = 11, F(n) = F(n-1) + F(n-2) (n>=2).
 

Input
Input consists of a sequence of lines, each containing an integer n. (n < 1,000,000).
 

Output
Print the word "yes" if 3 divide evenly into F(n).

Print the word "no" if not.
 

Sample Input
012345
 

Sample Output
nonoyesnonono
 

Author
Leojay
思路:开始做这道题时,常规的方法估计就是递归,然后求得f(n),然后再判断f(n)%3是否恒等于0。写代码时就有一种不祥的预感,感觉会超时,而且f(n)很可能会超过整型范围。结果是Runtime Error(STACK_OVERFLOW)
#include<iostream>using namespace std;int diaoyong(int n){if(n>=2)return diaoyong(n-1)+diaoyong(n-2);if(n==1)return 11;if(n==0)return 7;}int main(){int n;     while(scanf("%d",&n)!=EOF)       //f[4]=3 + 2=2+1 +1+0 =1+0+1+1+0=33+14=47{        if(diaoyong(n)%3==0)cout<<"yes"<<endl;elsecout<<"no"<<endl;}return 0;}
正确的解法是:实际可以找到规律的,仔细想想。让是不是能被3整除,能被3整除的,即余数是0的,输出yes,否则,输出no。所以我把对3取余的数列举一下:
                           余数(对3取余)
n=0      f(0)=7        1                     n=8      f(8)=322    1
n=1      f(1)=11      2                    n=9     f(9)=521     2
n=2      f(2)=18      0                     ……
n=3     f(3)=29       2                   可以看出循环周期为8.
n=4     f(4)=47       2                  n 对8取余,余数是2或者是6,输出yes,否  
n=5      f(5)=76      1                  则,输出no。
n=6      f(6)=123    0
n=7     f(7)=199     1
#include<iostream>using namespace std;int main(){    int n;    while(scanf("%d",&n)!=EOF)    {       if(n%8==2 ||n%8==6)           cout<<"yes"<<endl;       else           cout<<"no"<<endl;    }    return 0;}


0 0