Java Program to find GCD of two numbers

GCD of two numbers in Java:

GCD(Greatest Common Divisor) or we can say HCF(Highest Common Factor) of two numbers is the largest number(integer) that divides both the number. Or in other words, two numbers which are divisible by the same largest number leaving no remainder.
For example: GCD of 20 and 28 is 4 as shown in the image below.

GCD of two numbers in java

Java program two calculate GCD of two numbers using for loop and if statement:

In this example, we take the user input for the two numbers whose GCD need to be found and store it in num1 and num2. Then iterate through for loop for i less than equal num1 and i less than equal to num2

Inside for loop we set if statement to check for the divisibility 0f both num1 and num2 by i. If true then we set the value of current i to gcd. This iteration runs on until it finds the largest number that divides both num1 and num2.

Program:

The Output of GCD of two numbers in java