Intermediate Level

Implement the lcmArrayValues method that returns the least common multiple of all array values.

The input contains an integer array nums and its length size. Your task is to return the least common multiple of all values in the array.

The least common multiple is the smallest positive number that is divisible by every value in the array. For example, the LCM of [4,6,8] is 24.

Example 1

Input
nums (int[]) = [4,6,8]
size (int) = 3
Returns (int) 24

Example 2

Input
nums (int[]) = [3,4,5]
size (int) = 3
Returns (int) 60

Example 3

Input
nums (int[]) = [2,7]
size (int) = 2
Returns (int) 14

The LCM of two numbers can be calculated using their GCD: lcm(a, b) = abs(a * b) / gcd(a, b).

Start with the first array value as the current LCM. For each next value, calculate the LCM of the current result and that value.

After all values are processed, the result is the LCM of the full array.

Pseudocode:

function gcd(a, b):
    while b != 0:
        remainder = a % b
        a = b
        b = remainder
    return absolute value of a
function lcmArrayValues(nums, size):
    result = nums[0]
    for i from 1 to size - 1:
        result = absolute value of result * nums[i] / gcd(result, nums[i])
    return result
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.