题目介绍
-
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
题目分析
由题目中可以看出 f(n) 的取值范围是 0,1,2,3,4,5,6, 总共是7个数,因此 f(n-1) 和 f(n-2) 总共有 7*7 = 49种组合方法,于是对于一组给定的 A/B 的值, f(n)一共有 49 种可能的值,也就是说不管给定的 n 多大, 这组数中总共也只有 49 种数,因此可以推想这是一个循环,循环数为 49 。 经过验证,确实是这样的,因此可以相应的编写代码。
代码
#include <iostream>
using namespace std;
int main()
{
int A, B, n;
int fn[49];
fn[0] = 1;
fn[1] = 1;
while(cin>>A>>B>>n)
{
if(A==0 && B==0 && n==0)
{
break;
}
for(int i=2; i<49; i++)
{
fn[i] = (A * fn[i-1] + B * fn[i-2]) % 7;
}
cout<<fn[(n-1)%49]<<endl;
}
return 0;
}