Counting trailing zeros of numbers resulted from factorial

后端 未结 10 1713
北荒
北荒 2020-11-30 07:48

I\'m trying to count trailing zeros of numbers that are resulted from factorials (meaning that the numbers get quite large). Following code takes a number, compute the facto

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 08:40

    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.

提交回复
热议问题