欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 美食 > B : 斐波那契数列第n项Plus

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

2024/10/24 8:26:24 来源:https://blog.csdn.net/m0_73665762/article/details/140079191  浏览:    关键词: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*nowtemp[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*nowtemp[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;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com