Number of trailing zeroes in base 16 representation of N!

Given an integer N, the task is to find the number of trailing zeroes in the base 16 representation of the factorial of N.


Input: N = 6
Output: 1
6! = 720 (base 10) = 2D0 (base 16)

Input: N = 100
Output: 24


  • Number of trailing zeroes would be the highest power of 16 in the factorial of N in base 10.
  • We know that 16 = 24. So, the highest power of 16 is equal to the highest power 2 in the factorial of N divided by 4.
  • To calculate the highest power of 2 in N!, we can use Legendre’s Formula.

Below is the implementation of the above approach:





// C++ implementation of the approach
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
// Function to return the count of trailing zeroes
ll getTrailingZeroes(ll n)
    ll count = 0;
    ll val, powerTwo = 2;
    // Implementation of the Legendre's formula
    do {
        val = n / powerTwo;
        count += val;
        powerTwo *= 2;
    } while (val != 0);
    // Count has the highest power of 2
    // that divides n! in base 10
    return (count / 4);
// Driver code
int main()
    int n = 6;
    cout << getTrailingZeroes(n);




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.