Java Program to Find GCD of Two Numbers
In this section, we have covered different logics in Java programs to find GCD of two numbers.
Greatest Common Divisor: It is the highest number that completely divides two or more numbers. It is abbreviated for GCD. It is also known as the Greatest Common Factor (GCF) and the Highest Common Factor (HCF). It is used to simplify the fractions.
How to Find the Greatest Common Factor
Example: Find the GCF of 12 and 8.
Factors of 12: 1, 2, 3, 4, 6, 12
Factors of 8: 1, 2, 4, 8
Common Factors: 1, 2, 4
Greatest Common Factor: 4
Hence, the GCF of 12 and 8 is 4.
Algorithm to Find GCD
In Java, we can use the following ways to find the GCD of two numbers:
Using Java for loop
In the following program, we have initialized two numbers x=12 and y=8. After that, we have used a for loop that runs from 1 to the smallest of both numbers. It executes until the condition i <= x && i <= y returns true. Inside the for loop, we have also used if statement that tests the condition (x%i==0 && y%i==0) and returns true if both conditions are satisfied. At last, we have store the value of i in the variable gcd and print the same gcd variable.
GCD of 12 and 8 is: 4
Using Java while Loop
In the following example, we have used while loop to test the condition. The loop executes until the condition n1!=n2 becomes false.
GCD of n1 and n2 is: 10
In the above program, we can replace the while loop with the following logic that gives the same output.
GCD = 4
Using User-Defined Method
In the following program, we have defined a method named findGCD(). It contains the logic to find the GCD of two numbers. We have parsed two parameters a and b of type int.
Enter the First Number: 75 Enter the Second Number: 125 GCD of 75 and 125 = 25
Using the Euclidean Algorithm
The Euclidean Algorithm is an efficient method to compute GCD of two numbers. It is also known as Euclid's Algorithm. The algorithm states that:
Let's implement the above logic in a Java program.
Enter the two numbers: 11 33 The GCD of two numbers is: 11
Using Modulo Operator
In the following program, we have defined a recursive function named findGCD(). It parses two parameters a and b of type int. If the second number (b) is equal to 0, the method returns a as GCD, else returns a%b.
GCD of 112 and 543 is 1
Let's see another logic to find the GCD of two numbers.
GCD of 54 and 24 is 6
Next TopicJava Programs