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
原创粉丝点击