9. 斐波那契数列

  题目:写一个函数,输入n,求斐波那契(Fibonacci)数列的第n项。斐波那契数列的定义如下:
                             { 0                                    n = 0
                   f(n) = { 1                                    n = 1
                             { f(n-1) + f(n-2)                n > 1

  思路:
  1.传统递归算法:从上至下,也就是算f(5)的时候算f(4)和f(3),以及类推。然后这样会导致重复操作,f(5)得算f(4)和f(3),f(4)得算f(3)和f(2),这样f(3)就重复计算。

  2.改进循环算法:从下至上计算,保存中间值,直接进入下一环节的计算,而不是重新计算。

  测试用例
  1.功能测试(如输入3、5、10等)
  2.边界值测试(如输入0、1、2)。
  3.性能测试(输入较大的数字,如40、50、100等)


  传统递归算法:

#include<iostream>
#include<cstdio>
using namespace std;

long long Fibonacci(unsigned int n)
{
    if (n <= 0)
    {
        return 0;
    }

    if (n == 1)
    {
        return 1;
    }

    return Fibonacci(n - 1) + Fibonacci(n - 2);
}

//测试
void test1()
{
    long long result = Fibonacci(10);
    cout << result << endl;
}

void test2()
{
    long long result1 = Fibonacci(0);
    long long result2 = Fibonacci(1);
    long long result3 = Fibonacci(2);
    cout << result1 << " " << result2 << " " << result3 << endl;
}

void test3()
{
    long long result = Fibonacci(50);
    cout << result << endl;
}

int main()
{
    test1();
    test2();
    test3();

    return 0;
}

改进循环算法: 

#include<iostream>
#include<cstdio>
using namespace std;

long long Fibonacci(unsigned n)
{
    int result[2] = {0, 1};
    if (n < 2)
    {
        return result[n];
    }

    long long fibMinOne = 1;
    long long fibMinTwo = 0;
    long long fibN = 0;
    for (unsigned int i = 2; i <= n; i++)
    {
        fibN = fibMinOne + fibMinTwo;

        fibMinTwo = fibMinOne;
        fibMinOne = fibN;
    }

    return fibN;
}

//测试
void test1()
{
    long long result = Fibonacci(10);
    cout << result << endl;
}

void test2()
{
    long long result1 = Fibonacci(0);
    long long result2 = Fibonacci(1);
    long long result3 = Fibonacci(2);
    cout << result1 << " " << result2 << " " << result3 << endl;
}

void test3()
{
    long long result = Fibonacci(500);
    cout << result << endl;
}

int main()
{
    test1();
    test2();
    test3();

    return 0;
}

运行的时候,传统递归输入50就已经跑不动了,而改进循环的那个算法输入500一下子就跑出来了。

猜你喜欢

转载自my.oschina.net/134596/blog/1793848