美文网首页
Fibonacci序列

Fibonacci序列

作者: 凡之恒 | 来源:发表于2017-10-30 23:15 被阅读0次

递归法:

long int fibonacci(int input)
{
    long int result;

    if (input >= 2) {
        result = fibonacci(input-1) + fibonacci(input-2);
    } else {
        switch (input) {
        case 0:
            result = 0;
            break;
        case 1:
            result = 1;
            break;
        }   
    }   
    return result;
}

循环法:

long long int fibonacci(int input)
{
    long long int f0 = 0;
    long long int f1 = 1;
    long long int f2;
    int i;

    switch (input) {
    case 0:
        return f0;
    case 1:
        return f1;
    }

    for (i = 2; i <= input; i++)
    {
        f2 = f0 + f1;
        f0 = f1;
        f1 = f2;
    }

    return f1;
}
方法 时间复杂度
递归法 O(2^n)
循环法 O(n)

相关文章

网友评论

      本文标题:Fibonacci序列

      本文链接:https://www.haomeiwen.com/subject/vypcuxtx.html