Given a positive integer N, we have to find the total number of digits in the factorial of N raised to the power N, i.e,
Input: 4 Output: 6 Explanations: = = 331776. Total number of digits in 331776 is 6. Input: 5 Output: 11 Explanations: = = 24883200000 Total number of digits in 24883200000 is 11. Input: 2 Output: 1 Input: 1000 Output: 2567605
The idea of the solution is described below.
Brute force method: By brute force, we can simply compute N! in O(N) time and then multiply it n times but that will be a very slow method and would exceed both time and space because would be a huge number.
Let’s look at it more closely. We can break (N!)^N into simpler terms which are easy to compute. By taking common logarithm,
and we know,
Therefore we can reduce further.
Now we can compute the answer easily in O(N) time and without space limit exceeding.
So why is a valid answer to the problem?
We know that the total number of digits in a number N whose base is 10 can be easily found by taking ceil(log10 (N)). That is exactly done in the approach described above.
The code implementation of the above idea is given below.
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. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price.
In case you wish to attend live classes with industry experts, please refer Geeks Classes Live