GCD (HCF) in Java
Find the GCD or HCF in Java by replacing a pair with b and a % b until b is zero. Scanner supplies the values; this version expects non-negative inputs.
1import java.util.Scanner;23public 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 }1213 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();1920 System.out.println("GCD = " + gcd(a, b));21 sc.close();22 }23}
Sample Output
Enter first number: 24 Enter second number: 36 GCD = 12
(24,36) → (36,24) → (24,12) → (12,0). The helper returns 12.
In this one
- Find a common divisor without listing factors
- Trace remainder-based reduction
- Keep pair updates in the right order
How it works
- 1
Read a and b.
- 2
Save old b in temp.
- 3
Set b to a % b and a to temp.
- 4
Repeat until b is zero, then return a.
Edge cases
One value zero
Use 24 and 0
The helper returns 24 without entering the loop.
Both values zero
Use 0 and 0
This implementation returns 0 by convention. There is no greatest positive common divisor for that pair.
What's going on
The greatest common divisor, also called the highest common factor, is the largest positive number that divides both inputs exactly. For 24 and 36 it is 12. This can help simplify a fraction or split two quantities into equal-sized groups.
Scanner is the keyboard reader. The gcd helper uses repeated remainders. A remainder is the amount left after division, written with % in Java. It replaces the pair a, b with b, a % b until b becomes zero. The last non-zero value in a is the answer for positive inputs.
The temporary variable holds the old b while the pair changes. Do not assign a = b before calculating the remainder unless the old a has been saved too. This compact version is intended for non-negative inputs. It can return a negative value for negative inputs, so remove signs first if your task requires a positive GCD for all signed values.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What is GCD of 24 and 36?
Pick an answer to check it.
Question 2
What replaces b on each pass?
Pick an answer to check it.
Questions people ask
Are GCD and HCF different results?
No. They are two names for the same quantity.
Does input order matter?
No for positive inputs. The remainder process still reaches the same divisor.
Why stop when b is zero?
There is no remainder left, so the current a divides the previous pair exactly.