使用欧几里得算法计算两个数的最大公约数

来源:互联网 发布:下载录屏软件 编辑:程序博客网 时间:2024/06/04 08:52
public class Gcd {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please input the first number:");
        int m = scanner.nextInt();
        System.out.println("Please input the second number:");
        int n = scanner.nextInt();
        divisor(m, n);
        scanner.close();
    }

    // 使用欧几里得算法计算最大公约数
    public static int gcd(int max, int min) {

        if (max % min == 0) {
            System.out.println("the bigest divisor is:" + min);
            return min;
        }
        return gcd(min, max % min);
    }

    public static int divisor(int m, int n) {
        System.out.println("m:" + m + ", n:" + n);
        if (n > m) {
            m = m ^ n;
            n = m ^ n;
            m = m ^ n;
        }
        System.out.println("m:" + m + ", n:" + n);
        return gcd(m, n);
    }
}
0 0
原创粉丝点击