Fibonacci II-LintCode

204 篇文章 0 订阅

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:

对于给定的n, 需要求出Fn的最后四位

 注意事项
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)

样例
Given: n = 9
Return: 34

思路:
根据题目中给出的公式进行求解,即求出 (1110)n ( 1 1 1 0 ) n 的值。给出 22 2 ∗ 2 矩阵的乘法函数和幂函数,同时注意幂函数要使用二分法:

an={an2an2an12an12ann a n = { a n 2 ∗ a n 2 n 为 偶 数 a n − 1 2 ∗ a n − 1 2 ∗ a n 为 奇 数

得到Fn,并删除前面不必要的0。

#ifndef C949_H
#define C949_H
#include<iostream>
#include<string>
using namespace std;
class Matrix{
public:
    int a, b, c, d;
    Matrix(int a, int b, int c, int d)
    {
        this->a = a;
        this->b = b;
        this->c = c;
        this->d = d;
    }
};
class Solution {
public:
    /**
    * @param n: an integer
    * @return: return a string
    */
    string lastFourDigitsOfFn(int n) {
        // write your code here
        if (n == 0)
            return "0";
        else if (n == 1)
            return "1";
        Matrix matrix = matrixPow(n);
        //matrix.b表示Fn
        string res = to_string(matrix.b);
        int pos = 0;
        //清楚不必要的'0'
        for (int i = 0; i < res.size(); ++i)
        {
            if (res[i] != '0')
            {
                pos = i;
                break;
            }
        }
        return res.substr(pos);
    }
    //基本的2*2矩阵乘法,只取后四位,结果模10000
    Matrix matrixMul(Matrix A, Matrix B)
    {
        Matrix C(0, 0, 0, 0);
        C.a = (A.a*B.a + A.b*B.c) % 10000;
        C.b = (A.a*B.b + A.b*B.d) % 10000;
        C.c = (A.c*B.a + A.d*B.c) % 10000;
        C.d = (A.c*B.b + A.d*B.d) % 10000;
        return C;
    }
    //基本的2*2矩阵幂
    Matrix matrixPow(int n)
    {
        Matrix matrix(0, 0, 0, 0);
        if (n == 1)
            matrix = Matrix(1, 1, 1, 0);
        else if ((n & 1) == 0)
        {
            matrix = matrixPow(n >> 1);
            matrix = matrixMul(matrix, matrix);
        }
        else if ((n & 1) == 1)
        {
            matrix = matrixPow((n - 1) >> 1);
            matrix = matrixMul(matrix, matrix);
            matrix = matrixMul(matrix, Matrix(1, 1, 1, 0));
        }
        return matrix;
    }
};
#endif
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值