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
Return:
(int) 12
Example 2
Input:
a (int) = 7
b (int) = 5
Return:
(int) 35
Example 3
Input:
a (int) = 12
b (int) = 18
Return:
(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
Run your code to see the result.