一、题目描述
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).
二、输入
The input test file will contain a single line containing n (n ≤ 100).
There are multiple test cases!
三、输出
For each test case, print the Fn mod (10^9 + 7).
例如:
输入:9
输出:34
四、解题思路
使用动态规划思想,大问题由小问题组成。
第3项可以由1,2项求得,
第4项可以由2,3项求得,
…
第n项可以由n - 2, n - 1求得。
五、代码
#include <iostream>
using namespace std;
const long long int MODE = 1000000000+7; //当数太大是取模(题目要求)
int main()
{
int n;
while(cin >> n){
if(n == 0) cout << 0 << endl;
if(n == 1) cout << 1 << endl;
if(n >= 2){
int fn0, fn1, fn2;
fn0 = 0;
fn1 = fn0 + 1;
for(int i = 0; i < n - 1; i++)
{
fn2 = fn1 + fn0;
fn0 = fn1;
fn1 = fn2;
}
fn2 %= MODE;
cout << fn2 << endl;
}
}
return 0;
}