求两数的最大公约数

public class GreatestCommonDivisor {

    public static void main(String[] args) {
        GreatestCommonDivisor divisor = new GreatestCommonDivisor();
        System.out.println(divisor.getForMethodOne(15, 25));
        System.out.println(divisor.getForMethodTwo(16, 24));
        System.out.println(divisor.getForMethodThree(16, 24));
        System.out.println(divisor.gcd(16, 24));
    }

    //辗转相除法 欧几里得算法
    //a = kb + r,如果d是a,b的约数,那么d一定是也是r约数
    private int getForMethodTwo(int a, int b) {
        int big = Math.max(a, b);
        int small = Math.min(a, b);

        if (big % small == 0) {
            return small;
        }

        return getForMethodTwo(big % small, small);
    }

    //更相减损术
    //a = b + r,如果d是a,b的约数,那么d一定是r的约数
    private int getForMethodThree(int a, int b) {
        int big = Math.max(a, b);
        int small = Math.min(a, b);

        if (big % small == 0) {
            return small;
        }

        return getForMethodThree(big - small, small);
    }

    //移位算法
    private int gcd(int a, int b) {
        if (a == b) {
            //相等时为最大公约数
            return a;
        }
        if ((a & 1) == 0 && (b & 1) == 0) {
            //a,b均为偶数
            return gcd(a >> 1, b >> 1) << 1;
        } else if ((a & 1) == 0 && (b & 1) != 0) {
            //a偶数,b奇数
            return gcd(a >> 1, b);
        } else if ((a & 1) != 0 && (b & 1) == 0) {
            //a奇数,b偶数
            return gcd(a, b >> 1);
        } else {
            //a,b均为奇数
            int big = a > b ? a : b;
            int small = a < b ? a : b;
            //两个奇数的差必为偶数
            return gcd(big - small, small);
        }
    }

    //时间复杂度为O(n)
    private int getForMethodOne(int a, int b) {
        int big = Math.max(a, b);
        int small = Math.min(a, b);

        if (big % small == 0) {
            return small;
        }
        for (int i = small / 2; i > 1; i--) {
            if (big % i == 0 && small % i == 0) {
                return i;
            }
        }
        return 1;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值