Counting trailing zeros of numbers resulted from factorial

Your task is not to compute the factorial but the number of zeroes. A good solution uses the formula from http://en.wikipedia.org/wiki/Trailing_zeros (which you can try to prove)

def zeroes(n):
    i = 1
    result = 0
    while n >= i:
        i *= 5
        result += n/i  # (taking floor, just like Python or Java does)
    return result

Hope you can translate this to Java. This simply computes [n / 5] + [n / 25] + [n / 125] + [n / 625] + … and stops when the divisor gets larger than n.

DON’T use BigIntegers. This is a bozosort. Such solutions require seconds of time for large numbers.

Leave a Comment