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 不可以用遞歸公式求 會溢出 因為n比較大 (盡管我也是看見別人的博客才知道的) 對於公式 f[n] = A * f[n-1] + B * f[n-2]; 後者只有7 * 7 = 49 種可能,為什麼這麼說,因為對於f[n-1] 或者 f[n-2] 的取值只有 0,1,2,3,4,5,6 這7個數,A,B又是固定的,所以就只有49種可能值了。由該關系式得知每一項只與前兩項發生關系,所以當連續的兩項在前面出現過循環節出現了,注意循環節並不一定會是開始的 1,1 。 又因為一組測試數據中f[n]只有49中可能的答案,最壞的情況是所有的情況都遇到了,那麼那也會在50次運算中產生循環節。找到循環節後,就可以輕松解決了。(貼過來的) 代碼如下 (但是我提交了N次,只要i《=10000,就出現運行錯誤)...... 求指點
#include <stdio.h>
#include <math.h>
int f[10000];
int main()
{
int a,b,n,i;
f[1]=1;
f[2]=1;
while(scanf("%d%d%d",&a,&b,&n),a|b|n)
{
for(i=3; i<10000; i++)
{
f[i]=(a*f[i-1]+b*f[i-2])%7;
if(f[i]==1&&f[i-1]==1)
{
break;
}
}
n=n%(i-2);
f[0]=f[i-2];
printf("%d\n",f[n]);
}
return 0;
}