python和c递归性能的对比
性能上c真的快了很多
# 好比算这个汉诺塔游戏
# 假设有三根柱子,a,b,c,
# a柱子上有n个饼,上面的饼比下面的饼小,
# 现在要将饼全部原状挪到另外一个柱子上,要求不能把大饼放在小饼上,请问要挪动多少次。
#include<iostream>
using namespace std;
int fun_pull_hnt(int n){
int i = 0;
int times = 0;
while (i<n){
if (n==0){
times=n;
break;
}else if(n>0){
int t=times*2+1;
times = t;
i++;
}else{
times=0;
break;
}
}
return times;
}
int fun_hnt(int n){
if (n==1){
return 1;
}else{
return fun_hnt(n-1)+1+fun_hnt(n-1) ;
}
}
int main(){
int n;
while(true){
cout<<"问你有几块饼?" <<endl;
cin>>n;
if(n>0){cout<<fun_hnt(n)<<endl;}
else{
cout<<"请输入正确的数字"<<endl;
}
}
}
用c算30个饼的情况,用递归的方法,3秒就ok了。
python要110秒。

浙公网安备 33010602011771号