GCD (HCF) in Java

Find the greatest common divisor (HCF) of two numbers using Euclidean algorithm.

IntermediateModule 3: Loop ProgramsExample 11 of 25
gcd-hcf.java
1import java.util.Scanner;
2
3public class Main {
4 private static int gcd(int a, int b) {
5 while (b != 0) {
6 int temp = b;
7 b = a % b;
8 a = temp;
9 }
10 return a;
11 }
12
13 public static void main(String[] args) {
14 Scanner sc = new Scanner(System.in);
15 System.out.print("Enter first number: ");
16 int a = sc.nextInt();
17 System.out.print("Enter second number: ");
18 int b = sc.nextInt();
19
20 System.out.println("GCD = " + gcd(a, b));
21 sc.close();
22 }
23}

Output

Enter first number: 24
Enter second number: 36
GCD = 12

What's going on

We repeatedly replace (a, b) with (b, a % b) until b becomes 0.