• + 3 comments

    There are floor(n/5) + floor(n/25) + floor(n/125)+... zeroes at the end of n! Since 1/5 + 1/25 + 1/125 + ... = 1/4, we would expect (4n!) to be a very good lower bound for our answer. Also, the number of zeroes in successive values of n! only increase when n is a multiple of five. Using those two facts, we can create a starting value that requires very few checks even when n is very large.

    def fact_zeros(n):
        count = 0
        while n:
            count += n//5
            n //= 5
        return count
    
    def solve(n):
        test = ((4*n)//5) * 5
        while fact_zeros(test) < n:
            test += 5
        return test