POJ3070Fibonacci(矩阵快速幂+高效)

Fibonacci
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 11587   Accepted: 8229

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

0
9
999999999
1000000000
-1

Sample Output

0
34
626
6875

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:

.

题意:就是求斐波那契数列,只是有点大,递推也会超时,矩阵快速幂0ms,搞定;

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 using namespace std;
 6 const int N = 2;
 7 const int mod = 10000;
 8 struct Mat
 9 {
10     int mat[2][2];
11 };
12 Mat operator * (Mat a, Mat b)
13 {
14     Mat c;
15     memset(c.mat, 0, sizeof(c.mat));
16     for(int k = 0; k < N; k++)
17     {
18         for(int i = 0; i < N; i++)
19         {
20             for(int j = 0; j < N; j++)
21             {
22                 c.mat[i][j] = (c.mat[i][j] + a.mat[i][k] * b.mat[k][j] % mod) % mod;
23             }
24         }
25     }
26     return c;
27 }
28 Mat operator ^ (Mat a, int k)
29 {
30     Mat c;
31     for(int i = 0; i < N; i++)
32         for(int j = 0; j < N; j++)
33             c.mat[i][j] = (i == j);
34     while(k)
35     {
36         if(k & 1)
37             c = c * a;
38         a = a * a;
39         k >>= 1;
40     }
41     return c;
42 }
43 int main()
44 {
45     int n;
46     while(scanf("%d", &n) != EOF)
47     {
48         if(n == -1)
49             break;
50         if(n == 0)
51             printf("0
");
52         else if(n == 1)
53             printf("1
");
54         else
55         {
56             Mat a;
57             a.mat[0][0] = 1;
58             a.mat[0][1] = 1;
59             a.mat[1][0] = 1;
60             a.mat[1][1] = 0;
61             a = a ^ (n - 1);
62             printf("%d
",a.mat[0][0]);
63         }
64     }
65 
66     return 0;
67 }
View Code
原文地址:https://www.cnblogs.com/zhaopAC/p/5073684.html