【Fibonacci 數列前四位&後四位】hdu 3117

來源:互聯網
上載者:User

 

這題的前四位是參考別人的思路的,我發現求前幾位通常做法是取對數!

後四位不用說,當n>=40時,位元>8。另外,後四位的周期是15000,就這樣打表求出後四位。

至於前四位,就要用到Fibonacci 數列的通項公式,我看了百度百科後才知道這個公式==,另外,有趣的是當n無窮大,前一項與後一項之比逼近黃金分割0.618。。。orz。話說回來,an可以表示為t*10^k(t為>1的浮點數),取對數log10(an)=
log10(t) + k,其中0<log10(t) <1,所以取完對數減去整數部分就是log10(t) ,然後pow(10,log10(t) )還原t。注意,這裡有一個技巧,就是當n>=40時通式中括弧裡後一半趨向於無窮小,小到可以忽略。

上代碼:

#include <map>#include <set>#include <list>#include <queue>#include <deque>#include <stack>#include <string>#include <time.h>#include <cstdio>#include <math.h>#include <iomanip>#include <cstdlib>#include <limits.h>#include <string.h>#include <iostream>#include <fstream>#include <algorithm>using namespace std;#define LL long long#define MIN INT_MIN#define MAX INT_MAX#define PI acos(-1.0)#define N 2#define FRE freopen("input.txt","r",stdin)#define FF freopen("output.txt","w",stdout);#define MOD 10000int Fib[45] = {0,1,1,2,3};int last[20000] = {0,1,1,2,3};double gao = (1 + sqrt(5.0)) / 2.0;int main(){    int i,j;    for(i = 5; i < 15000; i++){        last[i] = (last[i-1] + last[i-2]) % MOD;    }    for(i = 5; i < 40; i++)Fib[i] = Fib[i-1] + Fib[i-2];    int n;    while(scanf("%d",&n)!=EOF){        int i,j;        if(n<40){            printf("%d\n",Fib[n]);        }        else{            double ans = n * log10(gao) - log10(5.0) / 2.0;            ans -= (int)ans;            ans = pow(10,ans);            while(ans < 1000){                ans *= 1000;            }            printf("%d...%4.4d\n",(int)ans,last[n%15000]);        }    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.