Learner Level

Implement the gcdOfTwoNumbers method that returns the greatest common divisor of two numbers.

The input contains two integers a and b. Your task is to return their greatest common divisor, also called GCD.

The GCD is the largest number that divides both integers without leaving a remainder. For example, the common divisors of 12 and 18 include 1, 2, 3, and 6, so the answer is 6.

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) = 24
b (int) = 36
Returns (int) 12

Use the Euclidean algorithm to find the GCD efficiently.

Repeatedly replace the larger problem with b and a % b. When b becomes 0, the current value of a is the greatest common divisor.

Pseudocode:

function gcdOfTwoNumbers(a, b):
    while b != 0:
        remainder = a % b
        a = b
        b = remainder
    return a
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.