//3-7输入两个数,求平方和
#include<iostream>
using namespace std;
int fun2(int m){
return m*m;
}
int fun1(int x, int y){
return fun2(x) + fun2(y);
}
int main(){
int a, b;
cout << "Please enter two integers(a and b): ";
cin >> a >> b;
cout << "The sum of square of a and b: " << fun1(a,b) << endl;
return 0;
}
//3-8阶乘
#include<iostream>
using namespace std;
unsigned fac(unsigned n){
unsigned f;
if (n == 0)
f = 1;
else
f = fac(n - 1) * n;
return f;
}
int main(){
unsigned n;
cout << "Enter a positive integer: ";
cin >> n;
unsigned y = fac(n);
cout << n << "! = " << y << endl;
return 0;
}
//3-9用递归法计算从n个人中选选k个人组成一个委员会的不同组合数。
//由n个人里选k个人的组合数 = 由n-1个人里选k个人的组合数 + 由n-1个人里选k-1个人的组合数
//当n = k 或 k = 0时, 组合数为1
#include<iostream>
using namespace std;
int comm(int n, int k){
if(k > n)
return 0;
else if(n == k || k == 0)
return 1;
else
return comm(n-1, k) + comm(n-1, k-1);
}
int main(){
int n, k;
cout << "Please enter two integers n and k: ";
cin >> n >> k;
cout << "C(n,k) = " << comm(n,k) << endl;
return 0;
}
//3-10有三根针A、B、C。A针上有N个盘子,大的在下,小的在上,要求把这N个盘子从A针移到C针
//在移动过程中可以借助B针,每次只允许移动一个盘,且在移动过程中在三根针上都保持大盘在下,小盘在上。
//将n 个盘子从A针移到C针可以分解为三个步骤:
// 1将A 上n-1个盘子移到 B针上(借助C针);
// 2把A针上剩下的一个盘子移到C针上;
// 3将n-1个盘子从B针移到C针上(借助A针)。
#include<iostream>
using namespace std;
void move(char src, char dest){
cout << src << " --> " << dest << endl;
}
void hanoi(int n, char src, char medium, char dest){//A到C,以B为过渡
if(n == 1)
move(src, dest);
else{
hanoi(n - 1, src, dest, medium);//A到B,以C为过渡
move(src, dest);
hanoi(n - 1, medium, src, dest);//B到C,以A为过渡
}
}
int main(){
int m;
cout << "Enter the number of diskes: ";
cin >> m;
cout << "the steps to moving" << m << " diskes: " << endl;
hanoi(m, 'A', 'B', 'C');
return 0;
}