C-Fibonacci123

Fibonacci的三种写法,当N稍大一点时,递归的慢就显出来了。
参数N表示求的是第N项斐波那契数(这里设前两项是0、1)
code:

#include<stdio.h>

long long Fibonacci1(long long n) {
    long long a = 0, b = 1, c, i;
    if(n == 1)
        return a;
    else if(n == 2)
        return b;
    else {
        for(i = 3; i <= n; i++) {
            c = a + b;
            a = b; b = c;
        }
        return c;
    }
}

long long Fibonacci2(long long n) {
    long long A[n], i;
    A[0] = 0; A[1] = 1;
    if(n == 1)
        return A[0];
    else if(n == 2)
        return A[1];
    else {
        for(i = 2; i < n; i++)
            A[i] = A[i - 1] + A[i - 2];
        return A[n - 1];
    }
}

long long Fibonacci3(long long n) {
    if(n == 1)
        return 0;
    else if(n == 2)
        return 1;
    else
        return Fibonacci3(n - 1) + Fibonacci3(n - 2);
}

int main() {
    long long N;
    scanf("%lld", &N);
    printf("%lld\n", Fibonacci1(N));
    printf("%lld\n", Fibonacci2(N));
    printf("%lld\n", Fibonacci3(N));
    return 0;
}
点赞