Monday, October 5, 2015

[19.3] the number of trailing zeros in N factorial

1. Example

5! = 1*2*3*4*5 = 120 -> 1 zero -> depends on # of 5s
           O          1          
26! = 1*2*3*4*5...*10*....*15*..*20*..*25
                          1      1          1        1        2





int count = 0;

for (int i = 5; N / i > 0; i*=5 )

{

count += N / i;

}

2. Implementation


public static int numZeros(int N)
{




    // validate the input
    if ( N < 0 )
    {
       System.out.println("Factorial is not defined for < 0");
       return 0;
    }
           




    int count = 0;
    for (int i = 5; N / i > 0; i*=5 )
    {
         count += N / i;// 45 = 5*9, (5,10,15,20,25,30,35,40,45)
    }




    return count;




}

3. Similar Ones Rule up front so that you can implement this correctly

No comments:

Post a Comment