题目:Fibonacci Again
题目链接:Problem - 1021 (hdu.edu.cn)
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
0
1
2
3
4
5
Sample Output
no
no
yes
no
no
no
解题思路及过程
此题目为斐波那契数列(Fibonacci sequence)的升级版。此题原题链接题目描述、样例输入输出为全英文,题目大概意思是:现有一个数列满足:F(0) = 7, F(1) = 11, F(n) = F(n-1) + F(n-2) (n>=2)。然后要求输入n,得到F(n),若F(n)能被3整除,输出"yes",否则,输出"no"。题目要求输入的N为N<1 000 000,而斐波那契数列增长的非常快,因此不能采用先算出F(n)的方法,然后再对3取模,很显然会超出数据范围。那么既然不能这么做,一定会有其他巧妙的方法。当不能用正常思维去求解,我们这时就要想到会不会出现规律。我们不妨大胆尝试写出几个数,观察有没有规律。为了方便求解,我们可以把原式 F(n) = F(n-1) + F(n-2) 等式左右两边都对3取模,即 F(n) %3 = (F(n-1) + F(n-2) ) %3,此式子由数论知识易知可以进一步等价于 F(n) %3 = (F(n-1) %3 + F(n-2) %3) %3。现在我们开始找规律:F(0)%3=1,F(1)%3=2,F(2)%3=(F(1)%3+F(0)%3)%3=0,同理 F(3)%3=2,F(4)%3=2,F(5)%3=1,F(6)%3=0,F(7)%3=1,F(8)%3=1,F(9)%3=2,这时可以发现 F(0)%3=1,F(1)%3=2 ,又 F(8)%3=1,F(9)%3=2,表明此时已出现循环,即一个完整的循环为:{1,2,0,2,2,1,0,1},既然已经出现了循环,那么此题就可以划为找规律题目了,此问题就迎刃而解了。
现在思路已经非常明确了,那么代码写起来就非常容易了。
下面附上我的 Accepted code:
#include<iostream>
using namespace std;
int main()
{
int a[8]={1,2,0,2,2,1,0,1},n;
while(cin>>n)
{
if(a[n%8]==0)
{
cout<<"yes"<<endl;
}
else
{
cout<<"no"<<endl;
}
}
return 0;
}