Monday, June 29, 2015

Trailing Zero of Factorial Numbers

Count trailing 0's from n factorial integers
ex: 10! = 3628800 = 2 trailing 0's

Input:
3
44
12
10

Output:
Case#1: 9
Case#2: 2
Case#3: 2


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.util.*;
import java.math.*;

public class trailingzero{
   public static void main(String[] args){
      Scanner scan = new Scanner(System.in);
      
      int cases=scan.nextInt();
      int[] num = new int[cases];
      
      for(int x=0;x<cases;x++)
         num[x] = scan.nextInt();
      
      for(int x=0;x<cases;x++){
         int count =0;                
         String sfact = ""+factorial(num[x]);
         for(int y=sfact.length();y>=0;y--)
         {
            if(!sfact.substring(y-1,y).equalsIgnoreCase("0"))
               break;
            else
               count++;
         }                  
         System.out.println("Case#"+(x+1)+": "+count);
      }
   }
   //this function for factorial number >=100
   public static BigInteger factorial(int number){
       BigInteger fact = new BigInteger("1"); 
       for ( int i = 2; i <= number; i++)
         fact = fact.multiply(BigInteger.valueOf(i));
       
       return fact;
   }
   
   
}

No comments:

Post a Comment