gcd of two numbers in java

Let’s learn to find gcd of two numbers in java.

gcd of two numbers in java

GCD of two numbers is the largest positive number that divides both numbers without remainder.

For example: GCD of 12 and 16 is 4

Now let’s see java program.

import java.util.Scanner;
public class GCDOfTwoNumbers 
{
   public static void main(String[] args) 
   {
      int a, b;
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter first number: ");
      a = sc.nextInt();
      System.out.print("Please enter second number: ");
      b = sc.nextInt();
      while(a != b) 
      {
         if(a > b)
         {
            a = a - b;
         }
         else
         {
            b = b - a;
         }
      }
      System.out.println("GCD of two numbers in java: " + b);
      sc.close();
   }
}


Output:

Please enter first number: 90
Please enter second number: 52
GCD of two numbers in java: 2


Also read – operators in java