ZhangZhihui's Blog  

Given an integer n, return the number of trailing zeroes in n!.

Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1.

 

Example 1:

Input: n = 3
Output: 0
Explanation: 3! = 6, no trailing zero.

Example 2:

Input: n = 5
Output: 1
Explanation: 5! = 120, one trailing zero.

Example 3:

Input: n = 0
Output: 0

 

Constraints:

  • 0 <= n <= 104

 

My Solution:

import math


class Solution:
    def trailingZeroes(self, n: int) -> int:
        val = math.factorial(n)
        cnt = 0
        while val % 10 == 0:
            val = val // 10
            cnt += 1
        return cnt

 

 

ChatGPT's Solution:

class Solution:
    def trailingZeroes(self, n: int) -> int:
        count = 0
        while n >= 5:
            n //= 5
            count += n
        return count

 

 

Explanation:

  • Trailing zeroes in n!n!n! come from factors of 10.

  • Since 10=2×510 = 2 \times 510=2×5, each trailing zero requires a pair of factors (2 and 5).

  • In factorials, there are usually more factors of 2 than 5, so counting the number of 5s in the prime factorization of n!n!n! gives the count of trailing zeroes.

  • We count multiples of 5, 25, 125, etc., because higher powers contribute extra factors of 5.

Example Calculation for n=100n = 100n=100:

  • 100//5=20100 // 5 = 20100//5=20 (multiples of 5)

  • 100//25=4100 // 25 = 4100//25=4 (multiples of 25)

  • 100//125=0100 // 125 = 0100//125=0 (multiples of 125)

  • Total = 20+4=2420 + 4 = 2420+4=24 trailing zeroes.

This algorithm runs in O(log⁡n)O(\log n)O(logn) time.

posted on 2025-04-04 23:20  ZhangZhihuiAAA  阅读(27)  评论(0)    收藏  举报