<OJ_Sicily>Fibonacci

来源:互联网 发布:淘宝云客服考试 编辑:程序博客网 时间:2024/06/01 15:31

Fibonacci_1

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 ≤ 100).

There are multiple test cases!

Output

 For each test case, print the Fn mod (10^9 + 7).

解题思路:一般斐波那契数列的求解有多种,下面通过递归和幂次数实现

#include <math.h>using namespace std;int Fibonacci_1(int n){    if(n==0 || n== 1)return n;       int fn = Fibonacci_1(n-1) +Fibonacci_1(n-2);    return fn %((int)pow(10,9)+7);           //每次都进行取模,防止数值过大溢出}int main(int argc, const char * argv[]) {    int n;    while(cin >> n)     {        cout << Fibonacci_1(n) << endl;    }    return 0;}                                 


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).

解题思路:相对于Fibonacci_1,不同的是,输入的n的范围值大了很多(n ≤ 2^31-1).考虑到时间限制,需要使用幂次方矩阵来解决这个问题。

斐波那契数列用矩阵表示如下:

#include <iostream>using namespace std;#define M 1000000007       struct Matrix{    long long v[2][2];};Matrix matrixMul(Matrix a, Matrix b) {      //两个矩阵相乘    Matrix temp;    for (int i = 0; i != 2; i++) {        for (int j = 0; j != 2; j++) {            temp.v[i][j] = 0;            for (int k = 0; k != 2; k++) {                temp.v[i][j] += a.v[i][k] * b.v[k][j];                temp.v[i][j] %= M;            }        }    }    return temp;}Matrix power(Matrix a, Matrix b, long long n) {    while (n) {        if (n & 1) {            b = matrixMul(b, a);        }        n >>= 1;        a = matrixMul(a, a);    }    return b;}int main(int argc, char* argv[]) {    Matrix a = {1, 1, 1, 0}, b = {1, 0, 0, 1};    long long n;    while (cin >> n) {        if (n == 0)            cout << 0 << endl;        else {            Matrix result = power(a, b, n - 1);            cout << result.v[0][0] << endl;        }    }    return 0;}                                 

后记:

1.刚开始的时候,并没有注意到数列递增的趋势,使用int是无法表示全部所需数列值的。因此后面统一变成了long long型

2.幂次方解决方法能够大大提高速度。


代码新手,有什么建议和意见欢迎提出

0 0