51Nod 1126 求递推序列的第N项(矩阵快速幂)
1 #include <iostream> 2 #include <algorithm> 3 #include <cmath> 4 #define MOD 7 5 #define N 2 6 using namespace std; 7 8 struct Matrix 9 { 10 long long v[N][N]; 11 }; 12 13 //矩阵间的乘法%m 14 Matrix matrix_mul(Matrix A, Matrix B, long long m) 15 { 16 Matrix ans; 17 18 for (int i = 0; i < N; i++) 19 { 20 for (int j = 0; j < N; j++) 21 { 22 ans.v[i][j] = 0; 23 for (int k = 0; k < N; k++) 24 { 25 ans.v[i][j] += (A.v[i][k] * B.v[k][j]) % m; 26 } 27 ans.v[i][j] %= m; 28 } 29 } 30 return ans; 31 } 32 33 //矩阵快速幂c^n%m 34 Matrix matrix_pow(Matrix C, long long n, long long m) 35 { 36 Matrix ans = { 1, 0, 0, 1 };//e 37 while (n) 38 { 39 if (n & 1) 40 ans = matrix_mul(ans, C, m); 41 C = matrix_mul(C, C, m); 42 n >>= 1; 43 } 44 return ans; 45 } 46 47 int main() 48 { 49 long long n; 50 int a, b; 51 cin >> a >> b >> n; 52 Matrix temp1 = { (a%MOD + MOD) % MOD, (b%MOD + MOD) % MOD, 1, 0 }; 53 Matrix temp2 = { 1, 0, 1, 0 }; // temp2{f[2],0,f[1],0}!!!!! 54 55 if (n < 2) 56 { 57 cout << 1 << endl; 58 return 0; 59 } 60 Matrix res = matrix_pow(temp1, n - 2, MOD); 61 res = matrix_mul(res, temp2, MOD); 62 cout << res.v[0][0] << endl; 63 return 0; 64 }