Learner Level

Implement the lcmOfTwoNumbers method that returns the least common multiple of two numbers.

The input contains two integers a and b. Your task is to return their least common multiple, also called LCM.

The LCM is the smallest positive number that is divisible by both numbers. For example, 12 is the smallest number divisible by both 4 and 6.

Example 1

Input
a (int) = 4
b (int) = 6
Returns (int) 12

Example 2

Input
a (int) = 7
b (int) = 5
Returns (int) 35

Example 3

Input
a (int) = 12
b (int) = 18
Returns (int) 36

Use the relationship between GCD and LCM.

First find the greatest common divisor of the two numbers using the Euclidean algorithm. Then calculate (a / gcd) * b. Dividing before multiplying helps avoid unnecessarily large intermediate values.

Pseudocode:

function lcmOfTwoNumbers(a, b):
    if a == 0 or b == 0:
        return 0
    gcdValue = gcd(a, b)
    return (a / gcdValue) * b
function gcd(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.