B : 斐波那契数列第n项Plus

Description

斐波那契数列即 1, 1, 2, 3, 5...,�(�)=�(�−1)+�(�−2) 。求斐波那契数列第 n 项

Input

每组数据给出 1≤�≤109 。

Output

斐波那契数列第 n 项 对 109+7 取模

Sample

#0
Input

Copy

1
2
20
100000000
Output

Copy

1
1
6765
908460138

代码有点丑陋,思路就是矩阵快速幂

#include <iostream>
using namespace std;
#include <cmath>
long long mod = 1e9 + 7;
long long quickPow(long long n, long long mod)
{
    long long a[4][4], now[4][4];
    a[1][1] = 1;
    a[1][2] = 0;
    a[2][1] = 0;
    a[2][2] = 1;

    now[1][1] = 0;
    now[1][2] = 1;
    now[2][1] = 1;
    now[2][2] = 1;

    long long temp[4][4];

    while (n > 0)
    {

        // cout << now[1][1] << " " << now[1][2] << endl;
        // cout << now[2][1] << " " << now[2][2] << endl;
        if (n % 2 == 1)
        {
            // a=a*now
            temp[1][1] = a[1][1];
            temp[1][2] = a[1][2];
            temp[2][1] = a[2][1];
            temp[2][2] = a[2][2];

            a[1][1] = ((temp[1][1] * now[1][1]) % mod + (temp[1][2] * now[2][1]) % mod) % mod;
            a[1][2] = ((temp[1][1] * now[1][2]) % mod + (temp[1][2] * now[2][2]) % mod) % mod;
            a[2][1] = ((temp[2][1] * now[1][1]) % mod + (temp[2][2] * now[2][1]) % mod) % mod;
            a[2][2] = ((temp[2][1] * now[1][2]) % mod + (temp[2][2] * now[2][2]) % mod) % mod;

            // cout << a[1][1] << " " << a[1][2] << endl;
            // cout << a[2][1] << " " << a[2][2] << endl;
        }
        // now=now*now
        temp[1][1] = now[1][1];
        temp[1][2] = now[1][2];
        temp[2][1] = now[2][1];
        temp[2][2] = now[2][2];

        now[1][1] = ((temp[1][1] * temp[1][1]) % mod + (temp[1][2] * temp[2][1]) % mod) % mod;
        now[1][2] = ((temp[1][1] * temp[1][2]) % mod + (temp[1][2] * temp[2][2]) % mod) % mod;
        now[2][1] = ((temp[2][1] * temp[1][1]) % mod + (temp[2][2] * temp[2][1]) % mod) % mod;
        now[2][2] = ((temp[2][1] * temp[1][2]) % mod + (temp[2][2] * temp[2][2]) % mod) % mod;
        n >>= 1;
    }
    return a[2][2];
}
int main()
{
    long long n;
    while (cin >> n)
    {
        cout << quickPow(n - 1, mod) << endl;
    }
    return 0;
}

  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值