1 利用递归设计此函数。
int p(int a,int b) { if(a>=b) return p(a-b,b)+1; else return 0; } //粘贴测试数据及运行结果: //测试数据 int main() { cout << p(3,1)<< endl; return 0; }
结果:
int akm(int m,int n) { if(m==0) return n+1; else if(m!=0&&n==0) return akm(m-1,1); else return akm(m-1,akm(m,n-1)); } //粘贴测试数据及运行结果: //测试数据 int main() { cout<<"akm(1,2):"<<akm(1,2)<<endl; cout<<"akm(2,1):"<<akm(2,1)<<endl; }
结果
3、利用递归实现汉诺塔算法
void towers(int n, char A, char C, char B) { if(n==1) { cout<<"move disk 1 from peg"<<A<<" to peg "<<C<<endl; return; } towers(n-1,A,B,C); //把圆盘n由A直接移至C cout<<"move disk "<<n<<" from peg"<<A<<" to peg "<<C<<endl; //把n-1个圆盘从B借助A移至C towers(n-1,B,C,A); } //测试数据 int main() { towers(3,'A','C','B'); return 0; }
结果