好玩的Fibonacci数列

1.原理:

不做过多解释,不会去翻高中数学教材

2.重要结论:

  1.前n项和 可以 用 n + 2项的数减一得到

 

计算方法:

  矩阵快速幂!!!

上板子题:

 

                                 Fibonacci
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 21213   Accepted: 14511

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <vector>
#include <iostream>
 
 
using namespace std;
 
typedef long long ll;
typedef vector<ll> vec;
typedef vector<vec> mat;
 
const ll  mod = 10000;
 
mat mul(mat & A, mat& B) {
    mat C(A.size(), vec(B[0].size()));
    for (int i = 0; i < A.size(); ++i)
        for (int k = 0; k < B.size(); ++k)
            if (A[i][k])
                for (int j = 0; j < B[0].size(); ++j)
                    C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % mod;
    return C;           
}
 
 
mat Pow(mat A, ll n) {
    mat B(A.size(), vec(A.size()));
    for (int i = 0; i < A.size(); ++i)
        B[i][i] = 1;
    for (; n; n >>= 1, A = mul(A, A))
        if(n & 1)
            B = mul(B, A);
    return B;
}
 
 
int main (){
    mat A(2);
 
    A.resize(2);//r行
    for (int k = 0; k < 2; ++k){
        A[k].resize(2);//每行为c列
    }
 
    A[0][0] = 1;
    A[0][1] = 1;
    A[1][0] = 1;
    A[1][1] = 0;
 
 
    ll n;
    while(cin >> n && n != -1) {
        if (n) {
            mat C = Pow(A, n - 1);
            cout << C[0][0] << endl;
        }
        else
            cout << 0 << endl;      
    }
}

 

 
posted @   LightAc  阅读(140)  评论(0编辑  收藏  举报
编辑推荐:
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
阅读排行:
· 开发的设计和重构,为开发效率服务
· 从零开始开发一个 MCP Server!
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· Ai满嘴顺口溜,想考研?浪费我几个小时
返回顶端
点击右上角即可分享
微信分享提示