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
看了这个数据,n的值有点大,第一反应就是矩阵快速幂,不过AC之后才感觉不用那么复杂,不过还是矩阵快速幂做比较放心
#include <iostream> #include <cstdio> using namespace std; struct Mat { int matrix[2][2]; }; Mat Multi(const Mat& a, const Mat& b) { int i, j, k; Mat c; for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { c.matrix[i][j] = 0; for (k = 0;k < 2; k++) c.matrix[i][j] += a.matrix[i][k] * b.matrix[k][j] % 7; c.matrix[i][j] %= 7; } } return c; }int main() { int A, B, n; int f[3]; while(scanf("%d%d%d",&A,&B,&n)!=EOF && !(A==0 && B==0 && n==0)) { Mat stand = {0, 1, B, A}; Mat e = {1, 0, 0, 1}; f[1]=1;f[2]=1; if (n <= 2) { printf("%d ", f[n]); continue; } Mat ans = e; Mat tmp = stand; n = n - 2; while(n) { if (n & 1) ans = Multi(ans, tmp); tmp = Multi(tmp, tmp); n >>= 1; } printf("%d ", (ans.matrix[1][0] * f[1] + ans.matrix[1][1] * f[2]) % 7); } return 0; }