zoukankan      html  css  js  c++  java
  • 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 }
    
    
  • 相关阅读:
    DOPE:基于蒸馏网络的全身三维姿态估计
    3D人体姿态重构
    Nginx+gunicorn+flask+docker算法部署
    MediaPipe中Box Tracking技术原理
    C++线程池
    MediaPipe加速流程和原理
    记一次illegal instruction问题定位
    如何阅读大工程代码(clickhouse版)
    zookeeper client原理总结
    go package依赖图自动生成
  • 原文地址:https://www.cnblogs.com/xingkongyihao/p/7220516.html
Copyright © 2011-2022 走看看