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

In this Java Program, you’ll learn how to swap two numbers using the Java programming language.  How to Swap Two...
  • Java
  • December 2, 2024
In this Java program , we will learn how to Find Largest Element in an Array in your Java program.   How to Find Largest Element...
  • Java
  • December 2, 2024
In this Java tutorial, we will learn how to add two integers in JAVA and storing the integer in an...
  • Java
  • December 2, 2024