Java Program to Find GCD of Two NumbersIn 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. Solution: 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 loopIn 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. FindGCDExample1.java Output: GCD of 12 and 8 is: 4 Using Java while LoopIn the following example, we have used while loop to test the condition. The loop executes until the condition n1!=n2 becomes false. FindGCDExample2.java Output: 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. FindGCDExample3.java Output: GCD = 4 Using UserDefined MethodIn 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. FindGCDExample4.java Output: Enter the First Number: 75 Enter the Second Number: 125 GCD of 75 and 125 = 25 Using the Euclidean AlgorithmThe 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. FindGCDExample5.java Output: Enter the two numbers: 11 33 The GCD of two numbers is: 11 Using Modulo OperatorIn 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. FindGCDExample6.java Output: GCD of 112 and 543 is 1 Let's see another logic to find the GCD of two numbers. FindGCDExample7.java Output: GCD of 54 and 24 is 6
Next TopicJava Programs
