Saturday, 30 November 2013

Find trailing zero of n factorial


Hello,
Here is small logic program to find trailing zero in n factorial. (n > 0). Here we are dividing the passing parameter with power of 5.
e.g .  Take 51.   How many trailing zero for 51 factorial. Let’s start. 
          Now Take 5  and divide 51 with 5 will ans. = 51/5 = 10  let  save  10 in variable.
          Now increase power of 5 = 52  = 25 and divide 51 with 25 = 51/25 = 2.
         Add ans in previous answer 10+2 = 12
         Now increase power of 5 = 53 = 125.  Now check 51/124  < 0.
         so it is not possible more to divide 51.
          So  your answer  = 12

Here is C# implementation for this logic.

        public static double ZeroCnt(int num)
        {
            int cnt, pow, number;
            cnt = 0;
            pow = 1;
            number = 5;
            while (number < num)
            {             
                cnt +=  num / number;
                pow ++;
                number = Convert.ToInt32(Math.Pow(5, pow));
            }
            return cnt;
        }


No comments:

Post a comment