Java Arithmetic Operators Modulus Operator calculate Greatest Common Divisor

Introduction

The greatest common divisor (GCD) of two integers is the largest integer that evenly divides each of the two numbers.


public class Main {

  public static void main(String[] args) 
  {//  w  ww  .  j av  a 2  s  .c  o m
    java.util.Scanner input = new java.util.Scanner( System.in );

    System.out.print( "Enter to number1: ");
    int number1 = input.nextInt();
    
    System.out.print( "Enter to number2: ");
    int number2 = input.nextInt();
    
    System.out.printf( "The GCD is: %d%n", GCD( number1, number2 ) );
  }
  
  public static int GCD( int a, int b )
  {
    while( b != 0 )
    {
      int r = a % b;
      
      a = b;
      b = r;
    }
    
    return a;
  }

}



PreviousNext

Related