📜  查找两个数的 GCD 或 HCF 的Java程序

📅  最后修改于: 2022-05-13 01:54:38.416000             🧑  作者: Mango

查找两个数的 GCD 或 HCF 的Java程序

GCD(即最大公约数)或 HCF(即最高公因数)是可以将两个给定数相除的最大数。

灯箱

例子:

HCF of 10 and 20 is 10, and HCF of 9 and 21 is 3.

因此,首先找到两个给定数字的所有质因数,然后找到两个给定数字中存在的所有这些因数的交集。最后,返回交集中元素的乘积。

注意:如果从较大的数字中减去较小的数字,则两个规定数字的GCD不会改变。



示例 1:

Java
// Java program to find GCD of two numbers
class GFG {
    // Gcd of x and y using recursive function
    static int GCD(int x, int y)
    {
        // Everything is divisible by 0
        if (x == 0)
            return y;
        if (y == 0)
            return x;
  
        // Both the numbers are equal
        if (x == y)
            return x;
  
        // x is greater
        if (x > y)
            return GCD(x - y, y);
        return GCD(x, y - x);
    }
  
    // The Driver method
    public static void main(String[] args)
    {
        int x = 100, y = 88;
        System.out.println("GCD of " + x + " and " + y
                           + " is " + GCD(x, y));
    }
}


Java
// Java program to find GCD of two 
// numbers using Euclidean algorithm
class geeksforgeeks {
    // Function to return gcd of x and y
    // recursively
    static int GCD(int x, int y)
    {
        if (y == 0)
            return x;
        return GCD(y, x % y);
    }
  
    // The Driver code
    public static void main(String[] args)
    {
        int x = 47, y = 91;
        System.out.println("The GCD of " + x + " and " + y
                           + " is: " + GCD(x, y));
    }
}


输出
GCD of 100 and 88 is 4

同样,您可以找到任意两个给定数字的 GCD 或 HCF。

一个有效的解决方案是在欧几里得算法中使用模运算符,这是应用于该主题的最重要的算法。

示例 2:

Java

// Java program to find GCD of two 
// numbers using Euclidean algorithm
class geeksforgeeks {
    // Function to return gcd of x and y
    // recursively
    static int GCD(int x, int y)
    {
        if (y == 0)
            return x;
        return GCD(y, x % y);
    }
  
    // The Driver code
    public static void main(String[] args)
    {
        int x = 47, y = 91;
        System.out.println("The GCD of " + x + " and " + y
                           + " is: " + GCD(x, y));
    }
}
输出
The GCD of 47 and 91 is: 1