Learner Level

Implement the method gcd that returns the greatest common divisor of two integers.

Return the greatest common divisor of two non-negative integers. The result is the largest integer that divides both values without a remainder.

The task is designed to test careful handling of edge cases, not only the most common input.

  • If one value is zero, return the other value.
  • If both values are zero, return 0.
  • Use repeated remainder reduction for an efficient solution.
Example 1
Input:
a (int) = 12
b (int) = 18
Return:
(int) 6
Example 2
Input:
a (int) = 7
b (int) = 13
Return:
(int) 1
Example 3
Input:
a (int) = 100
b (int) = 25
Return:
(int) 25
Example 4
Input:
a (int) = 0
b (int) = 9
Return:
(int) 9

Apply the Euclidean algorithm by repeatedly replacing gcd(a, b) with gcd(b, a % b) until the second value becomes zero.

Run your code to see the result.