Fibonacci数列
#include <iostream>
#include <ctime>
int fibonacci(int n) {
if (n <= 1) return 1;
return fibonacci(n-1)+fibonacci(n-2);
}
int Fibonacci(int lN,int lA=1,int lB=1)
{
if (lN==2||lN==1)
{
return lB;
}
return Fibonacci(lN-1,lB,lA+lB);
}
void runTime(int i) {
clock_t start, finish;
start = std::clock();
fibonacci(i);
finish = std::clock();
std::cout << i << ":" << (finish - start)/1000 << "ms" << std::endl;
start = std::clock();
Fibonacci(i);
finish = std::clock();
std::cout << "尾递归:" << i << ":" << (finish - start)/1000 << "ms" << std::endl;
}
int main() {
runTime(45);
runTime(46);
runTime(47);
return 0;