Number Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 124651 Accepted Submission(s): 30286
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).
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
Author
CHEN, Shunbao
Source
这题可以找规律,但是首先想到的还是矩阵快速幂。
![](https://images0.cnblogs.com/blog2015/758450/201506/151458302324918.png)
代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <cmath> 5 6 using namespace std; 7 8 #define MOD 7 9 #define MAXN 10 10 11 typedef struct MAT 12 { 13 int d[MAXN][MAXN]; 14 int r, c; 15 MAT() 16 { 17 r = c = 0; 18 memset(d, 0, sizeof(d)); 19 } 20 }MAT; 21 22 MAT mul(MAT m1, MAT m2, int mod) 23 { 24 MAT ans = MAT(); 25 ans.r = m1.r; 26 ans.c = m2.c; 27 for(int i = 0; i < m1.r; i++) 28 { 29 for(int j = 0; j < m2.r; j++) 30 { 31 if(m1.d[i][j]) 32 { 33 for(int k = 0; k < m2.c; k++) 34 { 35 ans.d[i][k] = (ans.d[i][k] + m1.d[i][j] * m2.d[j][k]) % mod; 36 } 37 } 38 } 39 } 40 return ans; 41 } 42 43 MAT quickmul(MAT m, int n, int mod) 44 { 45 MAT ans = MAT(); 46 for(int i = 0; i < m.r; i++) 47 { 48 ans.d[i][i] = 1; 49 } 50 ans.r = m.r; 51 ans.c = m.c; 52 while(n) 53 { 54 if(n & 1) 55 { 56 ans = mul(m, ans, mod); 57 } 58 m = mul(m, m, mod); 59 n >>= 1; 60 } 61 return ans; 62 } 63 64 int main() { 65 int n, m, t, a, b, k; 66 while(scanf("%d %d %d", &a, &b, &n) && a + b + n) { 67 MAT tmp, ans; 68 tmp.r = 2, tmp.c = 2; 69 ans.r = 2, ans.c = 1; 70 if(n == 1 || n == 2) { 71 printf("%d ", 1); 72 } 73 else { 74 tmp.d[0][0] = a; 75 tmp.d[0][1] = b; 76 tmp.d[1][0] = 1; 77 tmp.d[1][1] = 0; 78 ans = quickmul(tmp, n - 2, MOD); 79 printf("%d ", (ans.d[0][0]+ans.d[0][1]) % MOD); 80 } 81 } 82 }