Given a number n find the smallest number evenly divisible by each number 1 to n.
Input : n = 4 Output : 12 Explanation : 12 is the smallest numbers divisible by all numbers from 1 to 4 Input : n = 10 Output : 2520 Input : n = 20 Output : 232792560
If you observe carefully the ans must be the LCM of the numbers 1 to n.
To find LCM of numbers from 1 to n –
- Initialize ans = 1.
- Iterate over all the numbers from i = 1 to i = n.
At the i’th iteration ans = LCM(1, 2, …….., i). This can be done easily as LCM(1, 2, …., i) = LCM(ans, i).
Thus at i’th iteration we just have to do –
ans = LCM(ans, i) = ans * i / gcd(ans, i) [Using the below property, a*b = gcd(a,b) * lcm(a,b)]
Note : In C++ code, the answer quickly exceeds the integer limit, even the long long limit.
Below is the implementation of the logic.
The above solution works fine for a single input. But if we have multiple inputs, it is a good idea to use Sieve of Eratosthenes to store all prime factors. Please refer below article for Sieve based approach.
LCM of First n Natural Numbers
This article is contributed by Ayush Khanduri. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Smallest composite number not divisible by first N prime numbers
- Smallest n digit number divisible by given three numbers
- Number of pairs from the first N natural numbers whose sum is divisible by K
- Sum of first N natural numbers which are divisible by 2 and 7
- Sum of first N natural numbers which are divisible by X or Y
- Count numbers in a range with digit sum divisible by K having first and last digit different
- Check whether factorial of N is divisible by sum of first N natural numbers
- Check if factorial of N is divisible by the sum of squares of first N natural numbers
- Check if product of first N natural numbers is divisible by their sum
- Sum of first K numbers which are not divisible by N
- Check if the concatenation of first N natural numbers is divisible by 3
- Count the number of pairs (i, j) such that either arr[i] is divisible by arr[j] or arr[j] is divisible by arr[i]
- Smallest number divisible by n and has at-least k trailing zeros
- Smallest K digit number divisible by X
- C++ Program for Smallest K digit number divisible by X
- Java Program for Smallest K digit number divisible by X
- Smallest number with sum of digits as N and divisible by 10^N
- Smallest number greater than or equal to N divisible by K
- Length of the smallest number which is divisible by K and formed by using 1's only
- Find Nth smallest number that is divisible by 100 exactly K times