有一个序列满足:
F(0) = 7,
F(1) = 11,
F(n) = F(n-1) + F(n-2) (n>=2).的值,
输入 n (0<=n<=10^6) 要求判断能被 3 整除的 F (n)
输入描述
多行输入,每行一个正整数
输出描述
每行一个提示信息,若 F (n) 能被 3 整除,输出 “yes”,否则,输出 “no”
样例输入
0
1
2
3
4
5
样例输出
no
no
yes
no
no
no
#include<iostream>
using namespace std;
int main(){
int w,e1=7,e2=11,t,i;
while(cin>>w){{
if(w==0)
t=7;
if(w==1)
t=11;
if(w>=2){
for(i=w;i>1;i--)
e1=e1+e2;
e2=e2+e1;
t=e1;}}
if(t%3==0)
cout<<"yes"<<endl;
if(t%3!=0)
cout<<"no"<<endl;
}
return 0;
}
#include<iostream>
using namespace std;
int main(){
int w,e1=7,e2=11,t,i;
while(cin>>w)
{
e1=7,e2=11;//这里
{
if(w==0)
t=7;
if(w==1)
t=11;
if(w>=2){
for(i=w;i>0;i--)//这里
{
e2=e1+e2;//这里
e1=e2-e1; //这里
}
t=e1;
}
}
if(t%3==0)
cout<<"yes"<<endl;
if(t%3!=0)
cout<<"no"<<endl;
}
return 0;
}
补充下,题目要求N最大是1000000,那么计算e1 e2再判断,会导致e1 e2太大,超过int范围
所以可以在
e2=e1+e2;
e1=e2-e1;
下面加上2行
e1=e1%3;
e2=e2%3;
这样就不怕太大了。
你用循环表示这个递归算式是不对的。表示这个递归式可以用递归函数(代码如下),你可以像下面那个代码一样加一行输出在你的源代码看看问题。望采纳!!
#include<iostream>
using namespace std;
int F(int n)
{
if(n==0)
return 7;
else if(n==1)
return 11;
else
return F(n-1)+F(n-2);
}
int main(){
int w,e1=7,e2=11,t,i;
while(cin>>w){
t=F(w);
cout<<t<<endl;
if(t%3==0)
cout<<"yes"<<endl;
if(t%3!=0)
cout<<"no"<<endl;
}
return 0;
}