Skip to content

Latest commit

 

History

History
110 lines (74 loc) · 2.66 KB

File metadata and controls

110 lines (74 loc) · 2.66 KB

Java 程序:查找两个数字的 GCD

原文: https://www.programiz.com/java-programming/examples/hcf-gcd

在此程序中,您将学习在 Kotlin 中查找两个数字的 GCD。 这是通过在if else语句的帮助下使用forwhile循环来完成的。

两个整数的 HCF 或 GCD 是可以完全除以两个数(没有余数)的最大整数。

示例 1:使用for循环和if语句查找两个数字的 GCD

public class GCD {

    public static void main(String[] args) {

        int n1 = 81, n2 = 153, gcd = 1;

        for(int i = 1; i <= n1 && i <= n2; ++i)
        {
            // Checks if i is factor of both integers
            if(n1 % i==0 && n2 % i==0)
                gcd = i;
        }

        System.out.printf("GCD of %d and %d is %d", n1, n2, gcd);
    }
}

运行该程序时,输出为:

GCD of 81 and 153 is 9

这里,将要找到其 GCD 的两个数字分别存储在n1n2中。

然后,执行for循环,直到i小于n1n2为止。 这样,迭代 1 到两个数字中最小的所有数字以找到 GCD。

如果将n1n2都除以i,则将gcd设置为该数字。 一直进行到找到最大数(GCD)为止,该数将n1n2均除而无余数。


我们还可以使用while循环解决此问题,如下所示:

示例 2:使用while循环和if else语句查找两个数字的 GCD

public class GCD {

    public static void main(String[] args) {

        int n1 = 81, n2 = 153;

        while(n1 != n2)
        {
            if(n1 > n2)
                n1 -= n2;
            else
                n2 -= n1;
        }

        System.out.println("GCD = " + n1);
    }
}

运行该程序时,输出为:

GCD = 9

这是查找 GCD 的更好方法。 在此方法中,从较大的整数中减去较小的整数,然后将结果分配给保存较大整数的变量。 继续该过程,直到n1n2相等为止。

仅当用户输入正整数时,以上两个程序才能按预期工作。 这是第二个示例的一些修改,可以找到正整数和负整数的 GCD。


示例 3:正数和负数的 GCD

public class GCD {

    public static void main(String[] args) {

        int n1 = 81, n2 = -153;

        // Always set to positive
        n1 = ( n1 > 0) ? n1 : -n1;
        n2 = ( n2 > 0) ? n2 : -n2;

        while(n1 != n2)
        {
            if(n1 > n2)
                n1 -= n2;
            else
                n2 -= n1;
        }

        System.out.println("GCD = " + n1);
    }
}

运行该程序时,输出为:

GCD = 9