![]() |
VOOZH | about |
Given an integer n, find the number of digits that appear in its factorial, where factorial is defined as, factorial(n) = 1*2*3*4........*n and factorial(0) = 1
Examples :
Input: 5
Output: 3
Explanation: 5! = 120, i.e., 3 digitsInput: 10
Output: 7
Explanation: 10! = 3628800, i.e., 7 digits
Table of Content
A naive solution would be to calculate the n! first and then calculate the number of digits present in it. However as the value for n! can be very large, it would become cumbersome to store them in a variable .
To solve the problem follow the below idea:
We know,
log(a*b) = log(a) + log(b)Therefore
log( n! ) = log(1*2*3....... * n) = log(1) + log(2) + ........ +log(n)Now, observe that the floor value of log base 10 increased by 1, of any number, gives the number of digits present in that number. Hence, output would be : floor(log(n!)) + 1.
199
Time complexity: O(n log n) since calculating log in a loop
Auxiliary space: O(1) because it is using constant variables
199
Time complexity: O(1)
The time complexity of the above approach to count the number of digits in n! using Stirling's approximation and logarithms is O(1), meaning it is constant time complexity.
Auxiliary space: O(1)
In the next set, we'd see how to further optimize our approach and reduce the time complexity for the same program.