题目如下:
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
对于这一题,最开始的想法当然是用函数,递归直接算(这个显然不太现实也可以直接不看,跳到下面):
#include <iostream>
using namespace std;
int f(int a)
{
int b;
if(a==0)
{
b=7;
}
else if(a==1)
{
b=11;
}
else if(a>=2)
{
b=f(a-1)+f(a-2); //递归
}
return b;
}
int main()
{
int n;
while(cin>>n)
{
int m=f(n); //调用函数
if(m%3==0)
{
cout<<"yes"<<" "<<m<<endl;
}
else
{
cout<<"no"<<" "<<m<<endl;
}
}
return 0;
}
很显然,这样的做法在n变大的时候就会超时,这也是递归的占内存耗时间的一个很好的例子。至于迭代,我在看到超时之后,有点想法,但是发现这一题的特殊在于,每一个结果是否能被3整除是有规律的。
也就是,带入值就会发现:
0 no
1 no
2 yes
3 no
4 no
5 no
6 yes
...
10 yes
...
14 yes
...
18 yes
...
这样,规律就出来了。
从2开始,每隔三个数就会得到一个yes,那么我们由此可以得出一个肯定不会超时的代码:
#include <iostream>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
if((n-2)%4==0) //从2开始的之后的第四个数可以被三整除
{
cout<<"yes"<<endl;
}
else
{
cout<<"no"<<endl;
}
}
return 0;
}
附上C语言的写法:
#include <stdio.h>
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
if((n-2)%4==0) //从2开始的之后的第四个数可以被三整除
{
printf("yes\n");
}
else
{
printf("no\n");
}
}
return 0;
}