Friday, September 25, 2020

Given an integer n, return the number of trailing zeroes in n!

Approach: Let's take example say !5 = 5 x 4 x 3 x 2 x 1 = 120, it has 1 zero. If we see trailing zeros are equals to number of 10s in the factorial which we can say is equal to number of 5s (5 x 2) right. See it yourself that number of 5s are always less than number of 2s in factorial by definition.

Here is how we can count 5s -

         public int TrailingZeroes(int n)

        {

            int numsOfFives = 0;

            while (n >= 5)

            {

                numsOfFives += n / 5;

                n = n / 5;

            }

            return numsOfFives;

        }


Complexity: O(logn)

No comments:

Post a Comment