java program to calculate gcd of two numbers code example

Example: gcd of two numbers in java

// gcd of two numbers in java
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();
   }
}

Tags:

Java Example