杰瑞科技汇

Java如何高效求两数最大公约数?

Java求两个数的最大公约数

在Java中,有几种常见的方法可以求两个数的最大公约数(Greatest Common Divisor, GCD),以下是几种实现方式:

Java如何高效求两数最大公约数?-图1
(图片来源网络,侵删)

使用欧几里得算法(辗转相除法)

这是最常用且高效的方法:

public class GCD {
    public static int gcd(int a, int b) {
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }
    public static void main(String[] args) {
        int num1 = 56;
        int num2 = 98;
        System.out.println("GCD of " + num1 + " and " + num2 + " is: " + gcd(num1, num2));
    }
}

递归实现欧几里得算法

public class GCD {
    public static int gcd(int a, int b) {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }
    public static void main(String[] args) {
        int num1 = 56;
        int num2 = 98;
        System.out.println("GCD of " + num1 + " and " + num2 + " is: " + gcd(num1, num2));
    }
}

使用Java 8的Math类(Java 9+)

Java 9及以上版本提供了Math.gcd()方法:

public class GCD {
    public static void main(String[] args) {
        int num1 = 56;
        int num2 = 98;
        int gcd = Math.gcd(num1, num2); // Java 9+
        System.out.println("GCD of " + num1 + " and " + num2 + " is: " + gcd);
    }
}

处理负数的情况

如果需要处理负数,可以添加绝对值处理:

public class GCD {
    public static int gcd(int a, int b) {
        a = Math.abs(a);
        b = Math.abs(b);
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }
    public static void main(String[] args) {
        int num1 = -56;
        int num2 = 98;
        System.out.println("GCD of " + num1 + " and " + num2 + " is: " + gcd(num1, num2));
    }
}

处理大数(BigInteger)

对于非常大的数,可以使用BigInteger类:

Java如何高效求两数最大公约数?-图2
(图片来源网络,侵删)
import java.math.BigInteger;
public class GCD {
    public static BigInteger gcd(BigInteger a, BigInteger b) {
        while (!b.equals(BigInteger.ZERO)) {
            BigInteger temp = b;
            b = a.mod(b);
            a = temp;
        }
        return a.abs();
    }
    public static void main(String[] args) {
        BigInteger num1 = new BigInteger("12345678901234567890");
        BigInteger num2 = new BigInteger("98765432109876543210");
        System.out.println("GCD is: " + gcd(num1, num2));
    }
}

方法中,欧几里得算法是最常用且高效的,时间复杂度为O(log(min(a,b))),对于大多数应用场景,第一种或第二种方法已经足够。

Java如何高效求两数最大公约数?-图3
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇