Monday, 12 June 2023

Count of digits in factorial

 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 :




As we can see by doing this we can get count of numbers in the range, like 

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

Count of digits in factorial

 To count the digits in a factorial we must seek some optimization as you might also understand that getting all the product and storing the...