📜  euclids 算法 java gcd - Java (1)

📅  最后修改于: 2023-12-03 14:41:01.816000             🧑  作者: Mango

Euclid's Algorithm in Java for Finding GCD

Euclid's Algorithm is a well-known algorithm for finding the greatest common divisor (GCD) of two numbers. It involves repeatedly computing the remainder when one number is divided by the other, until the remainder is zero, at which point the other number is the GCD. In this article, we will discuss how to implement Euclid's Algorithm in Java.

Implementation
public static int gcd(int a, int b) {
    if (b == 0) {
        return a;
    }
    return gcd(b, a % b);
}

The above code snippet shows the implementation of Euclid's Algorithm in Java. It defines a public static method called gcd that takes two integers as parameters, and returns their GCD.

The code works by first checking if the second parameter b is zero. If it is, then the method simply returns the first parameter a, which is the GCD of the two numbers.

If the second parameter is not zero, the method returns the result of recursively calling the gcd method with the second parameter as the new first parameter, and the remainder of the first parameter divided by the second parameter as the new second parameter. This process continues until the second parameter eventually becomes zero.

Usage

You can call the gcd method from any other Java code by passing in two integer values as parameters. Here's an example:

int a = 1071;
int b = 462;
int gcdResult = gcd(a, b);
System.out.println("The GCD of " + a + " and " + b + " is " + gcdResult);

This will output:

The GCD of 1071 and 462 is 21
Conclusion

Euclid's Algorithm is a simple and effective way to find the GCD of two numbers. With the Java implementation shown above, you can easily incorporate this algorithm into your own Java programs.