LintCode 949. Fibonacci II (矩阵快速幂经典题)

  1. Fibonacci II
    中文English
    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

Example
Example1

Input: n = 9
Output: 34
Example2

Input: n = 30
Output: 2040
Notice
1.0 ≤ n ≤ 1,000,000,000
2.If the last four digits of Fn are all zeros, print ‘0’; otherwise, omit any leading zeros(print Fn mod 10000)

解法1:矩阵快速幂。时间复杂度O(logn)。
代码如下:

struct Matrix {
    long long matrix[2][2];
    
    Matrix() {
        for (int i = 0; i < 2; ++i) 
            for (int j = 0; j < 2; ++j)
                matrix[i][j] = 0;
    }
    
    void unit() {
        for (int i = 0; i < 2; ++i)
            for (int j = 0; j < 2; ++j)
                if (i == j) matrix[i][j] = 1;
    }
    
    Matrix operator * (const Matrix & m) const {
        Matrix tmp;
        for (int i = 0; i < 2; ++i) {
            for (int k = 0; k < 2; ++k) {
                if (matrix[i][k] == 0) continue;
                for (int j = 0; j < 2; ++j) {
                    tmp.matrix[i][j] += matrix[i][k] * m.matrix[k][j];
                    tmp.matrix[i][j] %= 10000;
                }
            }
        }
        return tmp;
    }
    
    Matrix power(int n) {
        Matrix result;
        result.unit();
        while(n) {
            if (n & 0x1) result = result * (*this);
            *this = (*this) * (*this);
            n /= 2;
        }
        return result;
    }
};

class Solution {
public:
    /**
     * @param n: an integer
     * @return: return a string
     */
    string lastFourDigitsOfFn(int n) {
        if (n == 0) return "0";
        Matrix A;
        A.matrix[0][0] = 1;
        A.matrix[0][1] = 1;
        A.matrix[1][0] = 1;
        A.matrix[1][1] = 0;
        
        Matrix m = A.power(n - 1);
        string answer;
        int p = m.matrix[0][0];
        if (p == 0) answer = "0";
        else {
            for (int i = 0; i < 4; ++i) {
                answer = to_string(p % 10) + answer;
                p /= 10;
            }
        }
        
        return answer;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值