直接用递归模拟会超内存,考虑到对7取余,A,B为定值,所以可以进行打表
1 #include <iostream> 2 #include <stdio.h> 3 using namespace std; 4 int main() 5 { 6 int a, b, n, i, t; 7 int f[50]; 8 f[1] = f[2] = 1; 9 while((3 == scanf("%d%d%d", &a, &b, &n)), a || b || n) 10 { 11 for(i = 3; i <= 49; ++i) 12 { 13 f[i] = (a * f[i-1] + b * f[i-2]) % 7; 14 if(1 == f[i] && 1 == f[i-1]) break; //cycle found 15 } 16 t = i - 2; //cycle 17 f[0] = f[t]; //将周期的最后一个放到0位置。实现f(n%t) 18 printf("%d\n", f[n%t]); 19 } 20 return 0; 21 }
时间: 2024-12-30 04:20:36