Java Program to Find GCD of two Numbers

Java Program to Find GCD of two Numbers

What are GCD?

In this Article, we will write a program to find GCD of two numbers in Java.
GCD stands for Greatest Common Divisor, also known as Highest Common Factor (HCF). It is the largest positive integer that divides two or more integers without leaving a remainder.

Program to Find GCD of Two Numbers Using For Loop:

Run
import java.util.*;

public class Main{
  public static void main(String[] args) {
    // Taking input of two numbers
    Scanner scn = new Scanner(System.in);
    int num1 = scn.nextInt();
    int num2 = scn.nextInt();
    
    // int n1 = 81, n2 = 153;
    
    // initializing answer variable
    int gcd = 1;

    for (int i = 1; i <= num1 && i <= num2; i++){
        if (num1 % i == 0 && num2 % i == 0)
            gcd = i;
    }
    System.out.println("GCD of " + num1 +" and " + num2 + " is " + gcd);
  }
}
Output:

GCD of 81 and 153 is 9

Program to Find GCD of Two Numbers Using while Loop:

Run
import java.util.*;

public class Main{
  public static void main(String[] args) {
    // Taking input of two numbers
    Scanner scn = new Scanner(System.in);
    int num1 = scn.nextInt();
    int num2 = scn.nextInt();
    
    int temp1 = num1;
    int temp2 = num2;
    // loop to calculate GCD of two numbers
    while(num1 != num2) {
      if(num1 > num2) {
        num1 -= num2;
      }
      else {
        num2 -= num1;
      }
    }
    System.out.println("GCD of " + temp1 +" and " + temp2 + " is " + num1);
  }
}
Output:

GCD of 81 and 153 is 9

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription