1.递归代码:
#include<iostream>
using namespace std;
int common(int x , int y){
if(x == y)
return x;
else if(x > y)
return common(x/2, y);
else
return common(x, y/2);
}
int main()
{
int x, y;
cout << "Enter two numbers: " << endl;
cin >> x >> y;
cout << common(x, y) << endl;
return 0;
}
运行结果:
Enter two numbers:
10 4
2
Process returned 0 (0x0) execution time : 3.552 s
Press any key to continue.
2.非递归代码:
#include<iostream>
using namespace std;
int main()
{
int x, y;
cout << "Enter two numbers : " << endl;
cin >> x >> y;
int m, n; //设置临时变量,
m = x;
n = y;
while(m != n)
{
if(m > n)
m = m/2;
else
n = n/2;
}
cout << m << endl;
return 0;
}
运行结果:
Enter two numbers :
10 4
2
Process returned 0 (0x0) execution time : 2.873 s
Press any key to continue.
比较分析:
由以上的运行结果来看,非递归的执行效率要高些。
一般而言,递归时间花销主要是函数的递归调用上,其空间开销大。
非递归效率一般要比递归高很多,但是要去模拟栈,必须得有循环,因此,时间开销增大。
所以递归算法用空间复杂度分析较合适,而改成的非递归算法用时间复杂度分析较合适。各有所长,根据实际情况来选择……
同时欢迎提出宝贵意见,以帮助我改进,不胜感激!!!
——桑海整理