编程之美2.7最大公约数问题Java版

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Test;

/**
 *
 * @author Administrator
 */
public class LookForGCD {

    public static void main(String[] args) {
        int x = 42;
        int y = 30;
        //解法一 辗转相除法   缺点:整数很大时,模运算中用到除法,很复杂
        int num = gcd1(x, y);
        System.out.println("num=" + num);
        //解法二              缺点:当x=1000000000 y =1时,要迭代很多很多次
        int num2 = gcd2(x, y);
        System.out.println("num2=" + num2);
        //解法三
        int num3 = gcd3(x, y);
        System.out.println("num3=" + num3);
    }

    private static int gcd1(int x, int y) {
        if (x < y) {
            return gcd1(y, x);
        }
        if (y != 0) {
            return gcd1(y, x % y);
        }
        return x;
    }

    private static int gcd2(int x, int y) {
        if (x < y) {
            return gcd1(y, x);
        }
        if (y != 0) {
            return gcd2(y, x-y);
        }
        return x;
    }

    private static int gcd3(int x, int y) {
        if (x < y) {
            return gcd3(y, x);
        }
        
        if (y == 0) {
            return x;
        } else {
            //判断x是否为偶数
            if (isEven(x)) {
                if(isEven(y)){
                    return (gcd3(x>>1,y>>1))<<1;
                }else{
                    return gcd3(x>>1,y);
                }
            }else{
                if(isEven(y)){
                    return gcd3(x,y>>1);
                }else{
                    return gcd3(y,x-y);
                }
            }
        }

    }

    private static boolean isEven(int x) {

        return x % 2 == 0;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值