51nod 1242 斐波那契数列的第N项

斐波那契数列的定义如下:
 
F(0) = 0
F(1) = 1
F(n) = F(n - 1) + F(n - 2) (n >= 2)
 
(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, ...)
给出n,求F(n),由于结果很大,输出F(n) % 1000000009的结果即可。
Input
输入1个数n(1 <= n <= 10^18)。
Output
输出F(n) % 1000000009的结果。
Input示例
11
Output示例
89

由于n最大有10^18这么大,直接用F(n) = F(n-1)+F(n-2)肯定不行的,这时可以用F(n+m-1) = F(n)*F(m)+F(n-1)*F(m-1)来做。
我是用递归来做的,当然,要把已经计算出来的值保存下来,不然同一个值会被计算很多次。


 1 #include <stdio.h>
 2 #include <iostream>
 3 #include <map>
 4 #define ll long long
 5 using namespace std;
 6 const int mod = 1000000009;
 7 map<ll,ll> mp;
 8 //f(n+m-1) = f(n)*f(m)+f(n-1)*f(m-1);
 9 ll fic(ll x){
10     if(x == 1 || x == 2) return 1;
11     if(x == 0) return 0;
12     if(mp[x] != 0) return mp[x];
13     if(x&1LL) {
14         ll a = x/2LL;
15         ll ans = ((fic(a+1LL)*fic(a+1LL))%mod+(fic(a)*fic(a)))%mod;
16         return mp[x] = ans;
17     }else{
18         ll a = x/2LL;
19         ll ans = ((fic(a)*fic(a+1LL))%mod+(fic(a-1LL)*fic(a)))%mod;
20         return mp[x] = ans;
21     }
22 }
23 int main(){
24     ll n;
25     cin >> n;
26     cout << fic(n) << endl;
27     return 0;
28 }

 


posted @ 2017-07-22 10:28  starry_sky  阅读(348)  评论(0编辑  收藏  举报