![]() |
VOOZH | about |
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.
Table of Content
The idea is to start with
res = 1and iteratively compute the LCM ofresand every number from1ton. We use:LCM(a, b) = (a * b) / GCD(a, b), After processing all numbers,resbecomes the LCM of all numbers from1ton.
60
Time Complexity: O(n log n)
Auxiliary Space: O(log n)
The idea is to use the fact that the LCM of numbers from
1toncontains the highest power of every prime that does not exceedn. For every primep ≤ n:
- Find the largest power
p^ksuch thatp^k ≤ n.- Multiply all such powers together.
Let us understand with example:
For n = 6:
LCM = 4 × 3 × 5 = 60
60
Time Complexity: O(n log log n)
Auxiliary Space: O(n)