3070 Fibonacci

Fibonacci
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 21048   Accepted: 14416

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

3070 Fibonacci.

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

3070 Fibonacci.

Also, note that raising any 2 × 2 matrix to the 0th power gives the identity matrix:

3070 Fibonacci.

 

 

裸的快速矩阵幂 >>=1就是/=2 前几天做题目头脑没转过弯来 好气

讲解参考 https://www.cnblogs.com/cmmdc/p/6936196.html

 1 #include <stdio.h>
 2 #include <iostream>
 3 #include <cstring>
 4 #include <vector>
 5 #include <queue>
 6 #include <set>
 7 #include <sstream>
 8 #include <algorithm>
 9 int N;
10 using namespace std;
11 const int si = 2, mod = 10000;
12 
13 struct mat {
14     int m[si][si];
15 };
16 
17 mat mul(mat A, mat B) {
18     mat tp;
19     for (int i = 0; i < si; i++) {
20         for (int j = 0; j < si; j++) {
21             tp.m[i][j] = 0;
22         }
23     }
24     for (int i = 0; i < si; i++) {
25         for (int j = 0; j < si; j++) {
26             for (int k = 0; k < si; k++) {
27                 tp.m[i][j] += A.m[i][k] * B.m[k][j];
28                 tp.m[i][j] %= mod;
29             }
30         }
31     }
32     return tp;
33 }
34 mat pow (mat A, int e){
35     mat tp;
36     for (int i = 0; i < si; i++) {
37         for (int j = 0; j < si; j++) {
38             if (i == j) tp.m[i][j] = 1;
39             else tp.m[i][j] = 0;
40         }
41     }
42     while (e) {
43         if (e & 1) {
44             tp = mul(tp, A);
45         }
46         A = mul(A, A);
47         e /= 2;
48     }
49     return tp;
50 }
51 int main() {
52     while (1) {
53         scanf("%d", &N);
54         if (N < 0) break;
55         if (N == 0) {
56             printf("%d\n", 0 % mod);
57             continue;
58         }
59         mat MA;
60         MA.m[0][0] = 1; MA.m[0][1] = 1;
61         MA.m[1][0] = 1; MA.m[1][1] = 0;
62         MA = pow(MA, N);
63         printf("%d\n", MA.m[1][0] % mod);
64     }
65     return 0;
66 }

 

上一篇:DP测试2补题


下一篇:比特币挖矿中的哈希率移动平均法