斐波那契数列算法

2021-12-14  本文已影响0人  jrglinux
/*fibonacci: 1 1 2 3 5 8 13 21 ...*/

#include "stdio.h"
#include "sys/time.h"
#include "string.h"
#include "time.h"

/*递归法, O((3/2)^n)*/
int fibo1(int n){
    if(n <= 2)
        return 1;
    else
        return fibo1(n-1) + fibo1(n-2);
}

/*迭代法, O(n)*/
int fibo2(int n){
    int x = 1, y = 1;
    int i = 0;
    for(i = 2; i < n; i++){
        y = x + y;
        x = y - x;
    }
    return y;
}

/*矩阵快速幂法, O(logn)
 *        |1,1|(n-1)
 * F(n) = |   |     * F(1)
 *        |1,0|
 */
void multiply(int F[2][2], int M[2][2]){
    int a = F[0][0] * M[0][0] + F[0][1]*M[1][0];
    int b = F[0][0] * M[0][1] + F[0][1]*M[1][1];
    int c = F[1][0] * M[0][0] + F[1][1]*M[1][0];
    int d = F[1][0] * M[0][1] + F[1][1]*M[1][1];
    F[0][0] = a;
    F[0][1] = b;
    F[1][0] = c;
    F[1][1] = d;
}

void power(int F[2][2], int n){
    if(n < 2)
        return;
    int M[2][2] = {{1,1},{1,0}};
    power(F, n/2);
    multiply(F, F);
    if( n & 1)
        multiply(F, M);
}

int fibo3(int n){
    int F[2][2] = {{1,1},{1,0}};
    if(!n)
        return 0;

    power(F, n-1);
    return F[0][0];
}

int main(int argc, char *argv[]){
    int n = 0;
    unsigned int Fn = 0;
    clock_t start, end;

    printf("input number:\n");
    scanf("%d", &n);

/*
    struct timeval tv1, tv2;
    unsigned long usecs = 0;

    gettimeofday(&tv1, NULL);
    Fn = fibo1(n);
    gettimeofday(&tv2, NULL);
    usecs = tv2.tv_sec*1000000 + tv2.tv_usec - tv1.tv_sec*1000000 - tv1.tv_usec;
    printf("fibo1, f(%d):%u, us:%ld\n", n, Fn, usecs);

    memset(&tv1, 0, sizeof(struct timeval));
    memset(&tv2, 0, sizeof(struct timeval));

    gettimeofday(&tv1, NULL);
    Fn = fibo2(n);
    gettimeofday(&tv2, NULL);
    usecs = tv2.tv_sec*1000000 + tv2.tv_usec - tv1.tv_sec*1000000 - tv1.tv_usec;
    printf("fibo2, f(%d):%u, us:%ld\n", n, Fn, usecs);
*/

    start = clock();
    Fn = fibo1(n);
    end = clock();
    printf("fibo1, f(%d):%u, sec:%f\n", n, Fn, (double)(end - start)/CLOCKS_PER_SEC);

    start = clock();
    Fn = fibo2(n);
    end = clock();
    printf("fibo2, f(%d):%u, sec:%f\n", n, Fn, (double)(end - start)/CLOCKS_PER_SEC);

    start = clock();
    Fn = fibo3(n);
    end = clock();
    printf("fibo3, f(%d):%u, sec:%f\n", n, Fn, (double)(end - start)/CLOCKS_PER_SEC);

    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读