题目链接:Number Sequence
问题描述
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(1) = 1,f(2) = 1,f(n) = (A * f(n-1) + B * f(n-2)) % 7,根据输入的A,B,n,计算f(n)的值。
解题思路
由于(1 <= A, B <= 1000, 1 <= n <= 100,000,000),使用递归暴力计算必定MLE(Memory Limit Exceeded),因此只能换其他的方法。
由于每次的结果都要对7取余,f(n)的结果只有0、1、2、3、4、5、6,七种可能,所以f(n-1)与f(n-2)的各自的取值也有7种可能,组合最多有7*7=49种可能,即最大的周期是49,在n>49时,f(n) = f(n%49),所以只要算出第一个周期的所有值,再利用周期规律,直接求f(n)即可。
代码
#include <iostream>
using namespace std;
int A, B;
int main(int argc, const char * argv[]) {
int n;
while (cin >> A >> B >> n) {
if (A == 0 && B == 0 && n == 0) {
break;
}
//初始化, f(1) = 1, f(2) = 1
int i, ans[50];
ans[1] = 1; ans[2] = 1;
//计算f(3)~f(49)的值
for (i = 3; i < 50; i++) {
ans[i] = (A * ans[i-1] + B * ans[i-2]) % 7;
}
//输出
cout << ans[n % 49] << endl;
}
return 0;
}
个人学习经验,欢迎各位指导