用了递归会超时啊,能优化一下吗?
A number sequence is defined as: 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)
输入格式
There are multiple lines of input. Every line is a test case. Each test case contains 3 integers A, B, and n on a single line (1 <= A, B <= 1000, 1 <= n <= 10000). Three zeros signal the end of input and this test case is not to be processed.
输出格式
For each test case, print the value of f(n) on a single line.
样例输入
将样例输入复制到剪贴板
1 1 3
1 2 10
0 0 0样例输出
2
5
这是我的代码:
#include<stdio.h>
int fab (int a,int b,int c);
int main()
{
int a,b,c;
while(1)
{
scanf("%d %d %d",&a,&b,&c);
if(a==0&&b==0&&c==0)
break;
else
{
printf("%d\n",fab(a,b,c));
}
}
}
int fab (int a,int b,int c)
{
if(c==1||c==2)
return 1;
else return (a*fab(a,b,c-1)+b*fab(a,b,c-2))%7;
}
能不能优化一下?递归会超时啊。谢谢。