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.
- Find maximum power of a number that divides a factorial
- Find sum of digits in factorial of a number
- Smallest number with at least n digits in factorial
- Sum of digits of a given number to a given power
- Number of digits in 2 raised to power n
- Find last five digits of a given five digit number raised to power five
- Largest power of k in n! (factorial) where k may not be prime
- Count digits in a factorial | Set 2
- Count digits in a factorial | Set 1
- Print last k digits of a^b (a raised to power b)
- Check if given number is a power of d where d is a power of 2
- Check whether product of digits at even places is divisible by sum of digits at odd place of a number
- Count of numbers between range having only non-zero digits whose sum of digits is N and number is divisible by M
- Maximize the given number by replacing a segment of digits with the alternate digits given
- Find the Largest number with given number of digits and sum of digits
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.