首页 > 代码库 > poj3070 矩阵快速幂
poj3070 矩阵快速幂
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 13438 | Accepted: 9562 |
Description
In the Fibonacci integer sequence, F0 = 0, F1 = 1, and Fn = Fn − 1 + Fn − 2 for n ≥ 2. For example, the first ten terms of the Fibonacci sequence are:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
An alternative formula for the Fibonacci sequence is
.
Given an integer n, your goal is to compute the last 4 digits of Fn.
Input
The input test file will contain multiple test cases. Each test case consists of a single line containing n (where 0 ≤ n ≤ 1,000,000,000). The end-of-file is denoted by a single line containing the number −1.
Output
For each test case, print the last four digits of Fn. If the last four digits of Fn are all zeros, print ‘0’; otherwise, omit any leading zeros (i.e., print Fn mod 10000).
Sample Input
099999999991000000000-1
Sample Output
0346266875
Hint
As a reminder, matrix multiplication is associative, and the product of two 2 × 2 matrices is given by
.
Also, note that raising any 2 × 2 matrix to the 0th power gives the identity matrix:
.
第一次写快速矩阵幂,按着Hint讲解的就好, 联想着快速幂,都有一个幂n,底数a,取余mod,还有一个ans = 1,作为初始;这里用
代替ans = 1, [1,1 ]作为底数a。。大概如此。。
[ 1,0]
1 #include <cstdio> 2 #include <iostream> 3 #include <cstring> 4 const int mod = 10000; 5 using namespace std; 6 struct mat { 7 int a[3][3]; 8 mat() { 9 memset(a, 0, sizeof(a));10 }11 mat operator *(const mat &o) const {12 mat t;13 for(int i = 1; i <= 2; i++) {14 for(int j = 1; j <= 2; j++)15 for(int k = 1; k <= 2; k++) {16 t.a[i][j] = (t.a[i][j] + a[i][k]*o.a[k][j])%mod;17 }18 }19 return t;20 }21 } a, b;22 23 int main() {24 int n;25 while(scanf("%d", &n) !=EOF && n!= -1) {26 a.a[1][1] = a.a[2][2] = 1, a.a[1][2] = a.a[2][1] = 0;27 b.a[1][1] = b.a[1][2] = b.a[2][1] = 1, b.a[2][2] = 0;28 if(n == 0) printf("0\n");29 else {30 n--;31 while(n > 0) {32 if(n&1) {33 a = b*a;34 n--;35 }36 n >>= 1;37 b = b*b;38 }39 printf("%d\n", a.a[1][1]);40 }41 }42 return 0;43 }
poj3070 矩阵快速幂