Calculating the number of zeroes at the end of a factorial The code seems to work, but, I always get the "Time Limit Exceeded" error (the time limit defined is 6 seconds). I even tried reducing the number of iterations but am still running short on time. I am basically trying to find the number of 5's and 2's, to obtain 10.

#include &lt;iostream&gt;

int number_counter(long int x, int base)
{
long int val = x;
unsigned int counter = 0;
for(long int i = x; i &gt;= 1;(!(i%base)?(i=i-base):i--))
{
    val =i;
    while((val % base) == 0)
    {
        counter++;
        val = val/base;
    }
}
return counter;

} 

int Zfact(long int num)
{
    unsigned int fives, twos;
    fives = number_counter(num, 5);
    twos = number_counter(num, 2);
    return (fives&gt;twos) ? twos : fives;
}
int main() {
    int T;                                  //T = Number of test cases.
    cin&gt;&gt;T;
    unsigned long int n;
    for(int i=0;i &lt; T;i++)
    {
        cin&gt;&gt;n;
        int zeroes = Zfact(n);
        cout&lt;&lt;zeroes&lt;&lt;endl;
    }

    return 0;
    }
This challenge looks familiar - I think I answered a similar challenge on our sister site, Programming Puzzles and Code Golf.  Those answers may not be as readable, though.

There's a couple of pieces of good news:


You don't need to count 2's in the prime factorization.  There will always be more 2's than 5's, so you can never have an unpaired 5.
You don't need to iterate over every number up to num if you see that we're just computing n/5 + n/25 + n/125 + ... (integer division).  If we define f(n) = n/5 + f(n/5) and f(0) = 0, we have a much faster version.  That can be implemented recursively, or fairly easily converted to iterative form.