运用递归的集中算法:最大公约数,阶乘,汉诺塔,倒酒

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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值