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 the last digit when factorial of A divides factorial of B
- Find maximum power of a number that divides a factorial
- Largest power of k in n! (factorial) where k may not be prime
- Smallest number with at least n digits in factorial
- Find sum of digits in factorial of a number
- Find the last two digits of Factorial of a given Number
- Check if given number is a power of d where d is a power of 2
- Count digits in a factorial | Set 2
- Count digits in a factorial | Set 1
- Numbers of Length N having digits A and B and whose sum of digits contain only digits A and B
- Minimum digits to be removed to make either all digits or alternating digits same
- Find power of power under mod of a prime
- Compute power of power k times % m
- Larger of a^b or b^a (a raised to power b or b raised to power a)
- Find the sum of power of bit count raised to the power B
- 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
- Check if a given number is factorial of any number
- 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 email@example.com. 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.