【求助】c语言,新手,我又 RE 又 MLE 又 TLE 了,不知道怎么办了,帮忙看看代码吧>_<
内存和时间要求:(其实还有一个64位什么的我不知道那是什么意思)Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
然后是题目,虽然是英文,但是单词都很简单,意思也很好理解,不看英文大概也可以了
Description
A number sequence is defined as follows:
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).
Input
The input consists of multiple test cases. Each test case contains 3 integers A, B and n on a single line (1 <= A, B <= 1000, 1 <= n <= 100,000,000). Three zeros signal the end of input and this test case is not to be processed.
Output
For each test case, print the value of f(n) on a single line.
Sample Input
1 1 3
1 2 10
0 0 0
Sample Output
2
5
这是我的第一个代码,用递归,但是RE了
#include<stdio.h>
int main()
{
int n,a,b;
int f(int a,int b,int n);
while(~scanf("%d%d%d",&a,&b,&n))
{
if(n!=0)
{
printf("%d\n",f(a,b,n));
}
}
return 0;
}
int f(int a,int b,int n)
{
if(n==1||n==2)
return 1;
else
return (a*f(a,b,n-1)+b*f(a,b,n-2))%7;
}
这是我的第二个代码,申请了一个动态变量f来储存结果,最后的结果是MLE了
#include<stdio.h>
#include<malloc.h>
int main()
{
int n,a,b,i;
int *f=(int*)malloc(sizeof(int)*100000000);
while(~scanf("%d%d%d",&a,&b,&n))
{
if(n!=0)
{
if(n==1||n==2)
printf("1\n");
else
{
f[0]=1;
f[1]=1;
for(i=2;i<n;i++)
f[i]=(a* f[i-1]+b*f[i-2])%7;
printf("%d\n",f[n-1]);
}
}
free(f);
}
return 0;
}
最后我垂死挣扎了一下,试着用两个循环来代替递归,又TLE了。。。
#include<stdio.h>
int main()
{
int n,a,b,i,sum1,sum2,sum;
while(~scanf("%d%d%d",&a,&b,&n))
{
if(n!=0)
{
if(n==1||n==2)
printf("1\n");
else
{
sum1=1;
sum2=2;
sum=0;
for(i=0;i<n-2;i++)
{
sum=(sum1*a+sum2*b)%7;
sum1=sum2;
sum2=sum;
}
printf("%d\n",sum);
}
}
}
return 0;
}
我实在没辙了,我是新手,很多东西不懂,求指教,只给大神你自己写的代码也好,顺便传授一下经验也好,帮帮忙~~~~~