Smallest number divisible by first n numbers - GeeksforGeeks
Given a number n find the smallest number evenly divisible by each number 1 to n.
Read full article from Smallest number divisible by first n numbers - GeeksforGeeks
Given a number n find the smallest number evenly divisible by each number 1 to n.
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 –
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)]
long long lcm(long long n){ long long ans = 1; for (long long i = 1; i <= n; i++) ans = (ans * i)/(__gcd(ans, i)); return ans;}