VOOZH about

URL: https://www.geeksforgeeks.org/dsa/lcm-of-given-array-elements/

⇱ LCM of given array elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

LCM of given array elements

Last Updated : 11 Jun, 2026

Given an array a[] of n numbers, find the Least Common Multiple (LCM) of all the elements of the array. The LCM of an array is the smallest positive number that is divisible by every element of the array.

Examples:

Input: a[] = [1, 2, 8, 3]
Output: 24
Explanation: 24 is the smallest number divisible by 1, 2, 8 and 3.

Input: a[] = [1, 8]
Output: 8
Explanation: 8 is the smallest number divisible by both 1 and 8.

[Naive Approach] Checking Multiples - O(max(a[i]) * n) Time and O(1) Space

The idea is to find LCM of two numbers by iterating through multiples of the larger number until we find one that is also divisible by the smaller number. We then extend this to the whole array by iteratively finding LCM of the current result with the next element.

Why can we compute LCM of an array one element at a time?

LCM satisfies the associative property:

LCM(a, b, c) = LCM(LCM(a, b), c)

Proof: A number x is divisible by a, b and c if and only if x is divisible by LCM(a, b) and c. The smallest such x is LCM(LCM(a, b), c). This extends to any number of elements: LCM(a₁, a₂, ... aₙ) = LCM(LCM(... LCM(LCM(a₁, a₂), a₃) ...), aₙ)

Example: arr = [1, 2, 8, 3]:
LCM(1, 2) = 2
LCM(2, 8) = 8
LCM(8, 3) = 24


Output
24

[Expected Approach] Using GCD - O(n * log(max(a[i]))) Time and O(1) Space

The idea is to use the mathematical relation lcm(a, b) = (a / gcd(a, b)) * b to efficiently compute LCM of two numbers. We then extend this to the whole array by iteratively computing LCM of the current result with the next element using GCD.

Why does LCM(a, b) = (a × b) / GCD(a, b)?

Every number can be expressed as a product of prime factors. GCD(a, b) contains the common prime factors and LCM(a, b) contains the all prime factors of both.

Since GCD × LCM covers all prime factors of both numbers exactly once:

GCD(a, b) × LCM(a, b) = a × b
Therefore:
LCM(a, b) = (a × b) / GCD(a, b) = (a / GCD(a, b)) × b

Example: a=4, b=6:
4 = 22 , 6 = 2 × 3
GCD(4, 6) = 2 (common factors)
LCM(4, 6) = 22 × 3 = 12
Verify: (4 × 6) / 2 = 12

Note: We divide before multiplying (a / GCD) × b to avoid integer overflow.


Output
24


Comment
Article Tags: