• POJ


    Fibonacci
    Time Limit: 1000MS   Memory Limit: 65536K
    Total Submissions: 9776   Accepted: 6964

    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水过
    #include <iostream>
    #include <cstdio>
    #include <cmath>
    #include <cstring>
    #include <cstdlib>
    #include <algorithm>
    using namespace std;
    
    const int MAXN = 2;
    struct Mat
    {
        int a[MAXN][MAXN];
    } ;
    
    Mat Multi(const Mat x, const Mat y, const int Mod)
    {
        Mat res;
        memset(res.a, 0, sizeof(res.a));
        for(int i = 0; i < MAXN; i++)
            for(int j = 0; j < MAXN; j++)
                for(int k = 0; k < MAXN; k++)
                    res.a[i][j] = (res.a[i][j] + x.a[i][k] * y.a[k][j]) % Mod;
        return res;
    }
    
    Mat Power(Mat base, int k, const int Mod)
    {
        Mat res;
        memset(res.a, 0, sizeof(res.a));
        for(int i = 0; i < MAXN; i++)
            res.a[i][i] = 1;
        while(k > 0) {
            if(k & 1)
                res = Multi(res, base, Mod);
            base = Multi(base, base, Mod);
            k = k >> 1;
        }
        return res;
    }
    
    int main()
    {
        int mod = 10000;
        int n;
        Mat base;
        base.a[0][0] = base.a[1][0] = base.a[0][1] = 1;
        base.a[1][1] = 0;
        while(cin >> n, n!=-1)
        {
            Mat res = Power(base, n, mod);
            printf("%d
    ", res.a[0][1]);
        }
        return 0;
    }
    


  • 相关阅读:
    阿里巴巴数据库分库分表的最佳实践
    Tomcat控制台日志乱码解决方案
    区块链:多链体系在提升性能的同时,怎么去保证单链被攻击性问题
    在 CentOS 7 1801 中安装 PostgreSQL-11
    为什么即使现在生意不太好做,还是有一批批的人开始做生意?
    投资十几万可以做点什么生意?
    理发店真是一个暴利行业吗?
    今日头条是怎么盈利的?
    中国都有哪些著名的风投失败的案例?
    基于语音应用的10项最佳实践
  • 原文地址:https://www.cnblogs.com/kunsoft/p/5312748.html
Copyright © 2020-2023  润新知