- Home
- Java Number Programs (ICSE Classes 9 / 10)
The Greatest Common Divisor (GCD) of two integers is
Java Number Programs (ICSE Classes 9 / 10)
The Greatest Common Divisor (GCD) of two integers is calculated by the continued division method. Divide the larger number by the smaller, the remainder then divides the previous divisor. The process repeats unless the remainder reaches to zero. The last divisor results in GCD.
Sample Input: 45, 20
Sample Output: GCD=5
Answer
import java.util.Scanner;
public class KboatGCD
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first number: ");
int a = in.nextInt();
System.out.print("Enter second number: ");
int b = in.nextInt();
while (b != 0) {
int t = b;
b = a % b;
a = t;
}
System.out.println("GCD=" + a);
}
}