Problem 10
Greatest Common Divisor
Easy · 10 pts · Math
Problem
You are given two non-negative integers A and B. Print their greatest common divisor (GCD): the largest positive integer that divides both of them exactly. If one of the numbers is 0, the GCD is the other number, since every integer divides 0. GCD(0, 0) is defined as 0. Euclid's algorithm is the standard method: repeatedly replace (A, B) with (B, A mod B) until B becomes 0; then A is the answer.
Input
Two non-negative integers A and B separated by a space.
Output
Print the GCD of A and B.
Constraints
0 <= A, B <= 1000000000
Example input
12 18
Example output
6
Explanation
The divisors of 12 are 1, 2, 3, 4, 6, 12 and the divisors of 18 are 1, 2, 3, 6, 9, 18. The largest number in both lists is 6. Euclid's algorithm gets there quickly too: (12, 18) → (18, 12) → (12, 6) → (6, 0), giving 6.