Number Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 80806 Accepted Submission(s): 18916
f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
Given A, B, and n, you are to calculate the value of f(n).
//////////////Runtime Error////////////////
#include<stdio.h>
int fun(int x,int y,int z)
{
int term;
if(z==1 || z==2)
term=1;
else
term=(fun(x,y,z-1)*x+fun(x,y,z-2)*y) % 7;
return term;
}
int main()
{
int a,b,n,result;
while(scanf("%d%d%d",&a,&b,&n))
{
if(a==0 && b==0 && n==0)
break;
result=fun(a,b,n);
printf("%d\n",result);
}
return 0;
}
#代碼(2)#循環遞歸,超時!
///////////////Time Limit Exceeded///////////
#include<stdio.h>
int main()
{
int a,b,n,f1,f2,f3,i;
while(scanf("%d%d%d",&a,&b,&n))
{
if(a==0 && b==0 && n==0)
break;
f1=1;f2=1;
for(i=3;i<=n;i++)
{
f3=(f2*a+f1*b)%7;
f1=f2;
f2=f3;
}
printf("%d\n",f3);
}
return 0;
}
#include <stdio.h>
int main()
{
int a,b,n,i,shuzu[10000];
while(scanf("%d%d%d",&a,&b,&n),a || b || n)
{
shuzu[1]=1;
shuzu[2]=1;
for(i=3;i<10000;i++)
{
shuzu[i]=(a*shuzu[i-1]+b*shuzu[i-2])%7;
if(shuzu[i]==1 && shuzu[i-1]==1) //如果出現連續的兩個1,則結束循環。
break;
}
n=n%(i-2); //因爲連續出現的兩個1是下次循環的初值,故不應計入本次循環次數,故要減去2
shuzu[0]=shuzu[i-2]; //本來n =0時,應將值計入shuzu[i-2],但是由於輸出方便,把shuzu[i-2]的值放入shuzu[0],即當n時i-2的整數倍時,輸出shuzu[0].
printf("%d\n",shuzu[n]);
}
return 0;
}