GCD of Two Numbers
Problem
Read two non-negative integers on one line. Print their greatest common divisor (GCD): the largest number that divides both. gcd(0, x) is x.
Constraints
- 0 <= a, b <= 10^12 (10^7 for the brute-force version)
Examples
Input
48 36
Output
12
Solutions
A common divisor of a and b also divides a % b. So the pair (a, b) can be replaced by the smaller pair (b, a % b) without changing the GCD. The numbers get small very fast.
/*
* Problem : Find the greatest common divisor (GCD) of two numbers.
* Input : Two non-negative integers on one line.
* Output : Their GCD.
* Approach: Use the Euclidean algorithm: replace (a, b) by (b, a % b).
* Time : O(log(min(a, b)))
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long first = scanner.nextLong();
long second = scanner.nextLong();
// Step 1: Repeat until the second number is 0.
while (second != 0) {
// Step 2: The GCD of (a, b) is the same as the GCD of (b, a % b). Example: gcd(48, 36) = gcd(36, 12).
long remainder = first % second;
first = second;
second = remainder;
}
// Step 3: When the second number is 0, the first number is the GCD. Example: gcd(12, 0) = 12.
System.out.println(first);
}
}
Hints (2)
- What is the GCD of 12 and 0?
- How does the remainder help to make the numbers smaller?