HDU 3117 Fibonacci Numbers(斐波那契前後四位,打表+取對+矩陣快速冪),hdufibonacci

來源:互聯網
上載者:User

HDU 3117 Fibonacci Numbers(斐波那契前後四位,打表+取對+矩陣快速冪),hdufibonacci
HDU 3117 Fibonacci Numbers(斐波那契前後四位,打表+取對+矩陣快速冪)

ACM

題目地址:HDU 3117 Fibonacci Numbers

題意: 
求第n個斐波那契數的前四位和後四位。 
不足8位直接輸出。

分析: 
前四位有另外一題HDU 1568,用取對的方法來做的。 
後四位可以用矩陣快速冪,MOD設成10000就行了。

代碼:

/**  Author:      illuz <iilluzen[at]gmail.com>*  Blog:        http://blog.csdn.net/hcbbt*  File:        3117.cpp*  Create Date: 2014-08-04 10:25:26*  Descripton:   */#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>using namespace std;#define repf(i,a,b) for(int i=(a);i<=(b);i++)typedef long long ll;const int N = 41;const int SIZE = 2;        // max size of the matrixconst int MOD = 10000;ll n;ll tab[N];double ans;struct Mat{    int n;    ll v[SIZE][SIZE];    // value of matrix    Mat(int _n = SIZE) {        n = _n;        memset(v, 0, sizeof(v));    }    void init(ll _v) {        repf (i, 0, n - 1)            v[i][i] = _v;    }    void output() {        repf (i, 0, n - 1) {            repf (j, 0, n - 1)                printf("%lld ", v[i][j]);            puts("");        }        puts("");    }} a, b;Mat operator * (Mat a, Mat b) {    Mat c(a.n);    repf (i, 0, a.n - 1) {        repf (j, 0, a.n - 1) {            c.v[i][j] = 0;            repf (k, 0, a.n - 1) {                c.v[i][j] += (a.v[i][k] * b.v[k][j]) % MOD;                c.v[i][j] %= MOD;            }        }    }    return c;}Mat operator ^ (Mat a, ll k) {    Mat c(a.n);    c.init(1);    while (k) {        if (k&1) c = a * c;        a = a * a;        k >>= 1;    }    return c;}double fib(int x) {    return -0.5 * log(5.0) / log(10.0) + ( (double)n) * log((sqrt(5.0) + 1) / 2) / log(10.0);}void table() {    // table    tab[0] = 0;    tab[1] = 1;    repf (i, 2, 40)        tab[i] = tab[i - 1] + tab[i - 2];}void pre4(int n) {    ans = fib(n);    ans -= floor(ans);    ans = pow(10.0, ans);    while (ans < 1000)        ans *= 10;    printf("%d", (int)ans);}void last4(int n) {     a.init(0);    a.v[0][0] = a.v[0][1] = a.v[1][0] = 1;    b = a ^ (n - 1);    printf("%04lld\n", b.v[0][0]);}int main() {    table();    while (~scanf("%lld", &n)) {        if (n < 40) {            printf("%lld\n", tab[n]);            continue;        }        pre4(n);        printf("...");        last4(n);    }    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.