This blog will soon be merged with

JavaByPatel

which explains each solution in detail, to visit new blog, click JavaByPatel

Wednesday, 20 May 2015

Count trailing 0(Zeros) in a Factorial of a number.


package miscellaneous;

//Write an algorithm which computes the number of trailing zeros in n factorial
//Trailing 0 will come into number when any number is multiplied by 10.
//So counting number of 10's present in a number will give you number of 0's present in a factorial.
//wait.. if number doesn't contain 10's factor but contains 2's and 5's factor then also 10 will come into picture as
//2*5 = 10, so now if we find out the number of 2 and 5 pairs present in a factor of number will give me number of 0s.
//Now for finding 2 and 5 pair, one thing we can see that any number where 5 factor will be present, it is sure 2 will be present as it will come before then 5.
//Eg: 5! = 5 * 4 * 3 * 2 * 1 = 5 * (2 * 2) * 3 * 2 = So number of 2's present in a number will always be more then 5.
//So instead of finding pair of 5 and 2 it is just fine to check 5 present in a number as 2 will obviously present where 5 is present to make up pair.
//One thing to observe is 
//number=20!, so number of 5's in 20 is 20/5 = 4, so there will be 4 zero in 20!.
//number=29!, so number of 5's in 29 is 29/5 = 5.8, so what to do here, it is sure that number of perfect 5 we will require to make 29! is 5 and 0.8 we can discard.
//So, it is not 5 zeros in 29! but is actually 6 0s (8841761993739701954543616000000)
//this situation we need to handle for numbers which itself are full multiple of 5.
//This means that there are 5 multiples of 5 in the number 29 – which is correct because there’s 
//5, 10, 15, 20, and 25. But wait, remember that 25 is special because it has 2 factors of 5 (because 5*5 is 25). 
//This means that it should count 2 times plus the 4 other factors of 5, which gives us 4+2 = 6.
//factorial of 25 is (15511210043330985984000000),
//so in general, you have to divide the number by 5, to findout how much 5 are present, you have to divide the number by 25 to findout how many 25 are present in a number as it will add extra 5 to number.
//and so on.

public class Trailing0sInFactorial {

 public static void main(String[] args) {
  int num=0;
  System.out.println(getTrailing0InFactorial(num));
 }
 
 public static int getTrailing0InFactorial(int num) {
  if(num<0)
   return -1;
  
  int count = 0;
  for (int i = 5; (num/i) > 0; i=i*5) {
   count = count + num/i;
  }
  return count;
 }
}



No comments:

Post a Comment