1,最大公约数
/**
* 欧几里得算法(求两个正整数的最大公约数)
*/
public class Gcd {
public int gcd(int m,int n){
int max=m;
if (m<n){
max=n;
n=m;
m=max;
}
if (n==0){
return m;
}else{
return gcd(n,m%n);
}
}
public static void main(String[] args){
Gcd gcd=new Gcd();
int temp=gcd.gcd(55,99);
System.out.println("最大公约数是" + temp);
}
}
2,阶乘
/**
* 求一个整数的阶乘的算法
*/
public class Fact {
public int fact(int n){
if (n==1){
return 1;
}else{
return n*fact(n-1);
}
}
public static void main(String[] args){
Fact fact=new Fact();
int temp=fact.fact(10);
System.out.println("阶乘的值为" + temp);
}
}
3,汉诺塔
/**
* 汉诺塔的实现(递归思想)
*/
public class HanNoTa {
int i=1;
public void hanNoTa(int n,char from,char depend,char to){
if (n==1){
moveIt(1,from,to);
}else{
hanNoTa(n-1,from,to,depend);
moveIt(n,from, to);
hanNoTa(n-1,depend,from,to);
}
}
private void moveIt(int n, char from, char to) {
System.out.println("第" + i++ +"步将盘子从" + from + "移到" + to);
}
public static void main(String[] args){
HanNoTa hanNoTa=new HanNoTa();
hanNoTa.hanNoTa(3,'A','B','C');
}
}
4,倒酒
/**
* 给定三个容量的杯子,倒出给定量的酒
*/
public class Wine {
private int b1=12;
private int b2=8;
private int b3=5;
private int m=10;
public void find(int bb1,int bb2,int bb3){
System.out.println("b1"+"的酒量为"+bb1+"--"+"b2"+"的酒量为"+bb2+"--"+"b3"+"的酒量为"+bb3);
if (bb1==m || bb2==m || bb3==m){
System.out.println("找到要求数量的酒瓶");
return;
}
if (bb2!=0&&bb3!=b3){
if (bb2+bb3<=b3){
find(bb1,0,bb3+bb2);
}else{
find(bb1,bb2-(b3-bb3),b3);
}
}else if (bb3==b3){
if (bb3+bb1<=b1){
find(bb1+bb3,bb2,0);
}else{
find(b1,bb2,bb3-(b1-bb1));
}
}else if (bb2==0){
if (bb1>=b2){
find(bb1-b2,b2,bb3);
}else{
find(0,bb1,bb3);
}
}
}
public static void main(String[] args){
Wine wine=new Wine();
wine.find(12,0,0);
}
}