How to Find GCD of Two Numbers in Java

 

When We talk about GCD (Greatest Common Divisor) of two numbers is the largest number that divides both without leaving a remainder. It's also called HCF (Highest Common Factor).


Example:

For numbers 12 and 18:

  • Factors of 12: 1, 2, 3, 4, 6, 12

  • Factors of 18: 1, 2, 3, 6, 9, 18

  • Common factors: 1, 2, 3, 6
    So, GCD is 6


Java Code – Using Euclidean Algorithm

java

public class GCD { public static int findGCD(int a, int b) { while (b != 0) { int temp = b; b = a % b; a = temp; } return a; } public static void main(String[] args) { int num1 = 12, num2 = 18; System.out.println("GCD: " + findGCD(num1, num2)); } }

Output:


GCD: 6

Conclusion

Here our GCD is a basic yet useful concept in Java. The Euclidean algorithm is fast and efficient for finding it. Practice with different numbers to get comfortable with the logic.

Comments

Popular posts from this blog

Python features

Master AWS with the Best Training in Pune – Join Technogeeks Today!