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
Returns (int) 6

Example 2

Input
a (int) = 7
b (int) = 13
Returns (int) 1

Example 3

Input
a (int) = 100
b (int) = 25
Returns (int) 25

Example 4

Input
a (int) = 0
b (int) = 9
Returns (int) 9

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

Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.