[Algorithms] – Count trailing zeroes in factorial of a number (Đếm số chữ số 0 tận cùng của n!)

Examples:
Input: n = 5
Output: 1 
Factorial of 5 is 20 which has one trailing 0.

Input: n = 20
Output: 4
Factorial of 20 is 2432902008176640000 which has
4 trailing zeroes.

Solution 1:

for (int i=1; i<=n; i++){
 j=i;
 while (j%5==0){
 j = j/5;
 dem = dem+1;
 }
 }

Solution 2:

int zero_count(int n){
return n<5?0: n/5+ zero_count(n/5);
}

Solution 3:

int findTrailingZeros(int  n)
{
    // Initialize result
    int count = 0;
    // Keep dividing n by powers of 5 and update count
    for (int i=5; n/i>=1; i *= 5)
          count += n/i;
    return count;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s