递归是一种功能,开始学时要理解系统怎样实现递归,然后以后写程序时就只需要找出一种递归“思路”就行了,不必再深究函数具体的实现步骤。
我们在用递归思路解决问题时,要根据递归的系统实现来考虑什么问题改用递归,什么问题不该用递归。
因为递归运行的内存消耗与 Recursive Tree (递归树)的deepth 有关,所以象Fibonaci 数列这种问题就不适合用递归。
现在就让我们看一下用递归与非递归实现Fibonaci的性能差别吧:
#include <iostream>
#include <ctime> // 因为要计算运行时间,所以需要调用cctime 里的 time( & time_t ) , double difftime( time_t , time_t )
using namespace std;
long fibonaci ( int n ) {
if ( n == 1 || n == 0 ) return n ;
else return fibonaci( n-1) + fibonaci( n-2) ;
}
long fibo( int n) {
if ( n<2) return n;
int p = 1, q = 1;
int temp;
for ( int i = 3; i<=n; ++i ) {
temp = q;
q = p+q;
p = temp; }
return q;
}
int main() {
time_t start, end;
int n;
double diff;
cout<<"Input the number to take factorial "<<endl;
cin>>n;
time( & start );
cout<<fibonaci ( n );
time( & end );
cout<<" Recursive function takes " << difftime( end, start ) <<" seconds "<<endl;
time( & start );
cout<<fibo ( n );
time( & end );
cout<<" Iterative function takes " << difftime( end, start ) <<" seconds "<<endl;
return main(); // 为了作完后不退出,继续执行main()函数
system( "pause" );
}
为了避免计算结果越界,所以我选了 35 , 执行结果如下:
Input the number to take factorial
35
9227465 Recursive func takes 2 seconds
9227465 Iterative func takes 0 seconds
Input the number to take factorial