Count digits in a factorial using Logarithm
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
Explanation: 5! = 120, i.e., 3 digits
Explanation: 10! = 3628800, i.e., 7 digits
Naive approach: To solve the problem follow the below idea:
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 (Unless you’re working in python!).
Count digits in a factorial using the property of logarithms:
To solve the problem follow the below idea:
log(a*b) = log(a) + log(b)
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.
Below is the implementation of the above approach:
1 3 7 199
Time complexity: O(N log N) since calculating log in a loop
Auxiliary space: O(1) because it is using constant variables
Approach 2: Using Stirling’s approximation formula to calculate the factorial and logarithm to count the number of digits.
- The countDigitsInFactorial(int n) function takes an integer n as input and returns the number of digits in the factorial of n. If n is negative, it returns 0. If n is 0 or 1, the factorial is 1, and it returns 1.
- In the countDigitsInFactorial(int n) function, the double x variable is declared and initialized using the Stirling’s approximation formula for the factorial. This formula provides a good approximation of the value of the factorial for large values of n.
- where e is the mathematical constant, and π is the mathematical constant pi.
- The formula used in this code is a simplified version of Stirling’s approximation that takes the logarithm of the above formula to get the number of digits in the factorial.
1 3 7 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.
This article is contributed by Ashutosh Kumar . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.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 write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
Please Login to comment...