/** * @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); } }