Friday, 26 May 2023

Trailing zeros of factorial

In this post i am going to explain the problem and how to solve it.

See the trailing zeros of a factorial means when we get a factorial of a number then the resultant might end with couple of zeros.
for example :
5! = 5 * 4 * 3 * 2 * 1 

= 120

 As we can see here in the number 120 we got a 0 likewise in other factorials we might get many more zeros so now the task is to identify those numbers which ends with zeros.

So to do this we must see the prime factorization of the resultant numbers meaning prime factorization of 120 = 2 * 2 * 2 * 3 * 5


And now if we see it clearly then the pattern which is making the trailing zeros happen is the 5*2 pair in the prime factorization as it would make 10 and multiplying any number with 10 would result in extra 0 to the end.

Now things to consider :
we can see there are more numbers of 2 than 5 which would be the general case for all numbers so we can simply count the number of 5's in the prime factorization of the number to get the count of number of zeros.

But there's a small catch to this logic, which is that there are numbers multiple of 5 which could be there in the prime factorization and since it's an already multiple of 5 so it would have an extra 5 inside it which we need to count.
for example : 25 or 125 so 
25 = 5 * 5 
and 
125 = 5 * 5 * 5

so as per our above logic we were counting all the 5's and also that we wont be calculating all the product and then prime factorization for real as we could get all the 5 at the end bcz it would be computationally expensive, right!!

So what we can do is divide the given number with all the multiple of 5 below that number meaning :

Example : 
5! = 120 = 5/5 = 1 

Similarly,
25/5 = 5
25/25 = 1

therefore 5+1 = 6 zeros

So the code should be :


 

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...