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) =
12b (int) =
18Returns (int)
6Example 2
Input
a (int) =
7b (int) =
13Returns (int)
1Example 3
Input
a (int) =
24b (int) =
36Returns (int)
12Use 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 aReady to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run