Given a number N. You are tasked with finding the smallest number S, such that N is a factor of S! (S factorial). N can be very large.
Input : 6 Output : 3 The value of 3! is 6 This is the smallest number which can have 6 as a factor. Input : 997587429953 Output : 998957 If we calculate out 998957!, we shall find that it is divisible by 997587429953. Factors of 997587429953 are 998957 and 998629.
We iterate from 1 to N, calculating factorial in each case. When we find a factorial that’s capable of having N as a factor, we output it. This method will be difficult to implement for large N, as the factorial can become very large.
Time Complexity: O(N^2)
Optimized Naive Approach
Instead of iterating from 1 to N, we use binary search. This is still a bad method, as we are still trying to calculate N!
Time Complexity O(N log N)
We can first calculate all the prime factors of N. We then reduce our problem to finding a factorial which has all the prime factors of N, at least as many times as they appear in N. We then binary search on elements from 1 to N. We can utilize Legendre’s Formula to check whether a number’s factorial has all the same prime factors. We then find the smallest such number.
At no point do we actually calculate a factorial. This means we do not have to worry about the factorial being too large to store.
Lagrange’s Formula runs in O(Log N).
Binary search is O(Log N).
Calculating prime factors is O(sqrt(N))
Iterating through prime factors is O(Log N).
Time complexity becomes: O(sqrt(N) + (Log N)^3)
This article is contributed by Aditya Kamath. 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.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.