NYOJ148 fibonacci数列(二)

fibonacci数列(二)

时间限制:1000 ms  |  内存限制:65535 KB
难度:3
 
描述

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.

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:

.

 
输入
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.
输出
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).
样例输入
0
9
1000000000
-1
样例输出
0
34
6875

 1 /*
 2 //代码一:找取模后的周期---因为是加法,所以完全可以根据取模后的周期推倒正确的结果
 3 #include <iostream>
 4 #include <cstdio>
 5 using namespace std;
 6 
 7 const int MAX = 15000 + 1;
 8 int fib[MAX];
 9 
10 int fun(int *fib, int mod)
11 {
12     fib[0] = 0;
13     fib[1] = 1;
14     int i = 2;
15     do
16     {
17         fib[i] = (fib[i - 1] + fib[i - 2]) % mod;
18         ++i;
19     }while(fib[i - 1] != 1 || fib[i - 2] != 0);
20     return i - 2;
21 }
22 
23 int main()
24 {
25     int T = fun(fib, 10000);
26     //cout << T;     T = 15000;
27     int n;
28     while(scanf("%d", &n) && n != -1)
29     {
30         printf("%d\n",fib[n % T]);
31     }
32     return 0;
33 }
34 
35 
36 */
37 
38 //代码二:二分幂
39 #include <cstdio>
40 #include <iostream>
41 
42 using namespace std;
43 
44 void fun(int a1[][2], int a2[][2])     // 相当于 a1 = a1 * a2
45 {
46     int c[2][2];
47     for(int i=0; i < 2; i++)
48         for(int j = 0; j < 2; j++)
49         {
50             c[i][j] = 0;
51             for(int k = 0; k < 2; k++)
52                 c[i][j] = (c[i][j] + a1[i][k] * a2[k][j])%10000;
53         }
54     for(int i = 0; i < 2; i++)
55         for(int j = 0; j < 2; j++)
56             a1[i][j] = c[i][j];
57 }
58 
59 int main()
60 {
61     int n;
62     while(scanf("%d", &n) && n != -1)
63     {
64         int a[2][2] = {{1,1}, {1,0}};
65         int b[2][2] = {{1,0}, {0,1}};     //初始化为单位矩阵,保存fib的值
66         if(n == -1) break;
67         while(n)                         //求 a 的 n 次幂
68         {
69             if(n & 1)
70                 fun(b, a);
71             fun(a, a);
72             n >>= 1;
73         }
74         printf("%d\n", b[1][0]); //最后n必然从1变为0,所以最后一次总要执行 fun(b, a);
75     }
76     return 0;
77 }
功不成,身已退
原文地址:https://www.cnblogs.com/dongsheng/p/2787414.html