Java Program to Find GCD of Two Numbers

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 SNIPPET
public 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 SNIPPET
class 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.  

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

Java is a popular programming language that is used to develop a wide range of applications. If you are a...
  • Java
  • March 6, 2023
Java is a programming language and computing platform that is used to create various types of applications. It is used...
  • Java
  • March 6, 2023
In this post, you’ll learn how to download and install JUnit in Eclipse so that you can use in your...
  • Java
  • October 9, 2022