sicily_course_1001


                                        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;
		} else
			quickmod(n);
	}
	return 0;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值