python和c遞迴效能的對比
阿新 • • 發佈:2018-11-04
效能上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秒。