In this Java program, we will learn how to find the GCD of two numbers using Java.
GCD (Greatest Common Divisor)- GCD is the highest number that divides two or more numbers completely.
How to Find GCD of two Numbers?
Example 1: using while loop and if statement
RUN CODE SNIPPETpublic class Main
{
public static void main(String[] args)
{
int n1=5, n2=60;
while(n1!=n2)
{
if(n1>n2)
n1=n1-n2;
else
n2=n2-n1;
}
System.out.printf("GCD of n1 and n2 is: " +n2);
}
}OUTPUT
GCD of n1 and n2 is: 5
Example 2: using for loop and if statement
RUN CODE SNIPPETclass Main {
public static void main(String[] args) {
int n1 = 66, n2 = 88;
int gcd = 1;
for (int i = 1; i <= n1 && i <= n2; ++i) {
if (n1 % i == 0 && n2 % i == 0)
gcd = i;
}
System.out.println("GCD of " + n1 +" and " + n2 + " is " + gcd);
}
}OUTPUT
GCD of 66 and 88 is 22
When both the numbers are divisible by a number called I, then it is set to be the GCD.