Problem 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
#include <iostream>
using namespace std;
int f[54] = {0, 1, 1};
int main()
{
int A, B, n, q = 1;
while (cin >> A >> B >> n && A && B && n)
{
for (int i = 3; i < 54; ++i)
{
f[i] = (A * f[i - 1] + B * f[i - 2]) % 7; //这里
if (i > 4)
{ if (f[i - 1] == f[3] && f[i] == f[4])
{
q = i - 4; //特别是这个地方
}
}
}
cout << f[n % q] << endl; //这里
}
return 0;
}
以下討論都限定
i>=1
:顯然
f(i) \in { 0 .. 6}
所以
<f(i-2), f(i-1)>
這個狀態空間是有限的, 最大不超過49所以
f(i)
是有週期的, 且49是一個週期然後枚舉出這個週期的全體, 找到和
f(n)
處於週期中相同位置的那個數補充:
你代碼中q不是最短週期, 其實可以在找到第一個週期時停下
當n是49的倍數時一定返回
f[0]=0
這可能是個bug