青蛙跳问题为什么是斐波那契数列

2021-02-15  本文已影响0人  拉普拉斯妖kk
#include<iostream> 
using namespace std; 

long long RecursiveFibonacci(unsigned int n)
{
    if(n == 1 || n == 2)
        return n;

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

int main() 
{
    cout << "RecursiveFibonacci(1)=" << RecursiveFibonacci(1) << endl;
    cout << "RecursiveFibonacci(2)=" << RecursiveFibonacci(2) << endl;
    cout << "RecursiveFibonacci(3)=" << RecursiveFibonacci(3) << endl;
    cout << "RecursiveFibonacci(5)=" << RecursiveFibonacci(5) << endl;
    cout << "RecursiveFibonacci(10)=" << RecursiveFibonacci(10) << endl;
    cout << "RecursiveFibonacci(50)=" << RecursiveFibonacci(50) << endl;
    cout << "RecursiveFibonacci(100)=" << RecursiveFibonacci(100) << endl;
}
#include<iostream> 
using namespace std; 

long long NonRecursiveFibonacci(unsigned int n)
{
    if(n == 1 || n == 2)
        return n;

    long long n1 = 1;
    long long n2 = 2;
    long long result = 0;
    for (unsigned int i = 3; i <= n; i++)
    {   
        result = n1 + n2;
        n1 = n2;
        n2 = result;
    }
    return result;
}

int main() 
{
    cout << "NonRecursiveFibonacci(1)=" << NonRecursiveFibonacci(1) << endl;
    cout << "NonRecursiveFibonacci(2)=" << NonRecursiveFibonacci(2) << endl;
    cout << "NonRecursiveFibonacci(3)=" << NonRecursiveFibonacci(3) << endl;
    cout << "NonRecursiveFibonacci(5)=" << NonRecursiveFibonacci(5) << endl;
    cout << "NonRecursiveFibonacci(10)=" << NonRecursiveFibonacci(10) << endl;
    cout << "NonRecursiveFibonacci(50)=" << NonRecursiveFibonacci(50) << endl;
    cout << "NonRecursiveFibonacci(100)=" << NonRecursiveFibonacci(100) << endl;
}
上一篇下一篇

猜你喜欢

热点阅读