求最大公约数

/**
 * @Author: subd
 * @Date: 2019/9/2 7:54
 * 求最大公约数
 */
public class GreatestCommonDivisor {
    /**
     * 暴力枚举法
     */
    public static long getGreatestCommonDivisor(long a, long b) {
        long big = a > b ? a : b;
        long small = a < b ? a : b;
        if (big % small == 0) {
            return small;
        }
        for (long i = small / 2; i > 1; i--) {
            if (small % i == 0 && big % i == 0) {
                return i;
            }
        }
        return 1;
    }

    /**
     * 辗转相除法
     */
    public static long getGreatestCommonDivisorV2(long a, long b) {
        long big = a > b ? a : b;
        long small = a < b ? a : b;
        if (big % small == 0) {
            return small;
        }
        return getGreatestCommonDivisorV2(big % small, small);
    }

    /**
     * 辗转相除法
     */
    public static long getGreatestCommonDivisorV3(long a, long b) {
        if (a == b) {
            return a;
        }
        long big = a > b ? a : b;
        long small = a < b ? a : b;
        /**
         * 循环次数
         */
        return getGreatestCommonDivisorV3(big - small, small);
    }

    /**
     * 优化方法
     */
    public static long gcd(long a, long b) {
        if (a == b) {
            return a;
        }
        if ((a & 1) == 0 && (b & 1) == 0) {
            return gcd(a >> 1, b >> 1) << 1;
        } else if ((a & 1) == 0 && (b & 1) != 0) {
            return gcd(a >> 1, b);
        } else if ((a & 1) != 0 && (b & 1) == 0) {
            return gcd(a, b >> 1);
        } else {
            long big = a > b ? a : b;
            long small = a < b ? a : b;
            return gcd(big - small, small);
        }

    }

    public static void main(String[] args) {
        Long time = System.currentTimeMillis();
        System.out.println(getGreatestCommonDivisor(435645562, 1234422));
        time = System.currentTimeMillis() - time;
        System.out.println("暴力枚举花费时间: " + time);
        time = System.currentTimeMillis() - time;
        System.out.println(getGreatestCommonDivisorV2(435645562, 1234422));
        time = System.currentTimeMillis() - time;
        System.out.println("辗转相除法花费时间: " + time);
        time = System.currentTimeMillis() - time;
        System.out.println(getGreatestCommonDivisorV3(435645562, 1234422));
        time = System.currentTimeMillis() - time;
        System.out.println("更相减损术花费时间: " + time);
        time = System.currentTimeMillis() - time;
        System.out.println(gcd(435645562, 123442));
        time = System.currentTimeMillis() - time;
        System.out.println("优化方法花费时间: " + time);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值