To count the digits in a factorial we must seek some optimization as you might also understand that getting all the product and storing them could lead to wastage of storage.
So what to do?
Lets see this :
1-9 = 1 digit
10-99 = 2 digit
100-999 = 3 digit
and so on.
we got the formula = floor[log(x)] + 1
but wait we need for factorial not a single digit right?
like factorial of 5! = 1 * 2 * 3 * 4 * 5
= 120
and we need to check for 120 not 1,2,3,4,5. so what to do?
well 5! can be written as 1 * 2 * 3 * 4 * 5 so no worries.
so lets put that in the equation.
floor[log(x)] = floor[log(120)] = floor[log(1*2*3*4*5)]
Now from the log formula we know we can add these simply.
floor[ log(1) + log(2) + log(3) + log(4) + log(5) ] + 1
There you have it!!!
Now code :
No comments:
Post a Comment