sicily_course_1001
来源:互联网 发布:昆仑数据科技面试 编辑:程序博客网 时间:2024/04/30 15:33
1001. Fibonacci 2
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, …
Given an integer n, your goal is to compute the last Fn mod (10^9 + 7).
Input
The input test file will contain a single line containing n (n ≤ 2^31-1).
There are multiple test cases!
Output
For each test case, print the Fn mod (10^9 + 7).
Sample Input
9
Sample Output
34
Hint
You may need to use "long long".
斐波那契数列:0 1 1 2 3 5 8 13 21 34 55 …………
公式:F(n+1) = F(n) + F(n-1) F(0) = 0 F(1) = 1
n的范围:n <= 2^31-1 即运算量很大,用一般方法容易超时
模10^9+7:结果不会大于10^9+7
算法分析:
一般求斐波那契数列的方法有两种:递归法和非递归法
在这么大的数据下,就算是非递归法也绝对超时,所以采用另一种更有效的方法:
矩阵快速幂
矩阵快速幂的方法这里有篇博客讲的很好了,不再多述:
http://www.cnblogs.com/yan-boy/archive/2012/11/29/2795294.html
这道题还需要一些知识:
同余定理
http://jiyuede.blog.163.com/blog/static/3325192120099232918625/
位操作
http://blog.csdn.net/shamohua/article/details/5783582
矩阵乘法
这个自学吧
斐波那契数列的矩阵算法
感觉看完这些应该就可以写出写出代码了……
代码:
/* * main.cpp * * Created on: Sep 26, 2014 * Author: xiangxiyun */#include <iostream>#include <string.h>#include <math.h>using namespace std;long long t;class matrix {public:long long a[2][2];matrix() {a[0][0] = 0;a[0][1] = 0;a[1][0] = 0;a[1][1] = 0;}matrix operator*(matrix);} origin, res;//矩阵乘法,重载*,每计算一次矩阵乘法求一次模,同余定理matrix matrix::operator*(matrix m) { matrix tmp; for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) { for(int k = 0; k < 2; k++) tmp.a[i][j] += (a[i][k] * m.a[k][j])%t; } } return tmp;}//矩阵计算,位操作void quickmod(long long n) {while (n) {if (n & 1)res = res * origin;n >>= 1;origin = origin * origin;}cout << res.a[1][0]%t<< endl;}void ini() {//将res初始为单位矩阵res.a[0][0] = 1;res.a[0][1] = 0;res.a[1][0] = 0;res.a[1][1] = 1;//初始为斐波那契计算需要的矩阵origin.a[0][0] = 1;origin.a[0][1] = 1;origin.a[1][0] = 1;origin.a[1][1] = 0;}int main() {long long n;while (cin >> n) {t = pow(10, 9) + 7;ini();if (n == 0) {cout << '0' << endl;} elsequickmod(n);}return 0;}
0 0
- sicily_course_1001
- MySQL查询表内重复记录
- 《白纸醋》每个月免费送的手机费跟扣扣币你不要?
- uva10382Watering Grass
- Java关键字final、static使用总结
- 【BZOJ】【P2819】【Nim】【题解】【链剖线段树】
- sicily_course_1001
- 学习
- 2014 ACM/ICPC 牡丹江赛区网络赛解题报告汇总
- asp.net上传压缩文件
- 关于报错you cannot combine custom titles with other title features
- Error building Player: Win32Exception: ApplicationName='E:/adt-20140702/sdk\tools\zipalign.exe', Com
- openstack页面自定义插件使用详解(django、ajax、post)(zTree为例)
- UDP中的Connect
- 随想