VOOZH about

URL: https://www.geeksforgeeks.org/dsa/lcm-first-n-natural-numbers/

⇱ LCM of First n Natural Numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

LCM of First n Natural Numbers

Last Updated : 3 Jun, 2026

Given a number n, find an integer denoting the smallest number divisible by each number from 1 to n.

Examples:

Input: n = 3
Output: 6
Explanation: 6 is the smallest number divisible by 1, 2 and 3.

Input: n = 6
Output: 60
Explanation: 60 is the smallest number divisible by all from 1 to 6.

Using LCM of Every Number - O(n log n) Time O(log n) Space

The idea is to start with res = 1 and iteratively compute the LCM of res and every number from 1 to n. We use: LCM(a, b) = (a * b) / GCD(a, b), After processing all numbers, res becomes the LCM of all numbers from 1 to n.


Output
60

Time Complexity: O(n log n)
Auxiliary Space: O(log n)

Using Prime Powers / Sieve - O(n log log n) Time O(n) Space

The idea is to use the fact that the LCM of numbers from 1 to n contains the highest power of every prime that does not exceed n. For every prime p ≤ n:

  • Find the largest power p^k such that p^k ≤ n.
  • Multiply all such powers together.

Let us understand with example:
For n = 6:

  • Highest power of 2 ≤ 6 is 2^2 which is 4
  • Highest power of 3 ≤ 6 is 3*1 which 3
  • Highest power of 5 ≤ 6 is 5*1 which is 5

LCM = 4 × 3 × 5 = 60


Output
60

Time Complexity: O(n log log n)
Auxiliary Space: O(n)

Comment
Article Tags:
Article Tags: