1000. Fibonacci

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

Sample Input

9

Sample Output

34

本题比较简单,由于最多只需要计算到第100个斐波那契序列。所以直接用long long利用for循环方法得到答案。代码如下。
#include <iostream>
using namespace std;
int main()
{
    int n;
    while(cin>>n)
    {
        long long f0=0, f1=1;
        if(n==0) cout << 0 << endl;
        else if(n==1) cout << 1 << endl;
        else{
            long long f2;
            for(int i=2;i<=n;i++)
            {
                f2=f0+f1;
                f0=f1;
                f1=f2;

            }
            f2=f2%(1000000007);
            cout << f2 << endl;
        }
    }
    return 0;
}             

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, ple Input
9

Sample Output

34

Hint

 You may need to use “long long”.

#include <cmath>
#include <cstring>
using namespace std;
#define MOD 1000000007
struct matrix
{
    long long a[2][2];
};

matrix mul(matrix x,matrix y)
{
    matrix m;
    memset(m.a,0,sizeof(m.a));

    for(int i=0;i<2;i++)
        for(int j=0;j<2;j++)
            for(int k=0;k<2;k++)
                m.a[i][j]=(m.a[i][j]+x.a[i][k]*y.a[k][j])%MOD;
    return m;
}

void power(int n)
{
    matrix t,result;
    t.a[0][0]=1;
    t.a[0][1]=1;
    t.a[1][0]=1;
    t.a[1][1]=0;
    memset(result.a,0,sizeof(result.a));

    for(int i=0;i<2;i++)    result.a[i][i]=1;
    while(n)
    {
        if(n&1) result=mul(result,t);
        t=mul(t,t);
        n=n>>1;
    }
    cout << result.a[0][1] << endl;
}

int main()
{
    int n;
    while(cin>>n)
    {
        power(n);
    }
    return 0;
}                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值