172. Factorial Trailing Zeroes [easy] (Python)

本文介绍了如何计算给定整数n的阶乘n!尾部0的个数的方法。利用数学原理,通过迭代或递归的方式,在O(logn)的时间复杂度内解决此问题。

题目链接

https://leetcode.com/problems/factorial-trailing-zeroes/

题目原文

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

Note: Your solution should be in logarithmic time complexity.

题目翻译

给定一个整数n,返回n!尾部0的个数。你的解法的时间复杂度要控制在O(logn)。

思路方法

所有的尾部的0可以看做都是2*5得来的,所以通过计算所有的因子中2和5的个数就可以知道尾部0的个数。实际上,2的个数肯定是足够的,所以只需计算5的个数即可。
要注意,25=5*5是有两个5的因子;125=5*5*5有3个5的因子。比如,计算135!末尾0的个数。
首先135/5 = 27,说明135以内有27个5的倍数;27/5=5,说明135以内有5个25的倍数;5/5=1,说明135以内有1个125的倍数。当然其中有重复计数,算下来135以内因子5的个数为27+5+1=33。

思路一

迭代求解。

代码

class Solution(object):
    def trailingZeroes(self, n):
        """
        :type n: int
        :rtype: int
        """
        res = 0
        while n > 0:
            n = n/5
            res += n
        return res

思路二

递归求解。

代码

class Solution(object):
    def trailingZeroes(self, n):
        """
        :type n: int
        :rtype: int
        """
        return 0 if n == 0 else n / 5 + self.trailingZeroes(n / 5)

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.youkuaiyun.com/coder_orz/article/details/51590478

`math.factorial(i)` 是 Python 标准库 `math` 中的一个函数,用于计算整数 `i` 的**阶乘**(即 `i! = i × (i-1) × ... × 1`)。以下是详细说明: --- ### **函数定义** ```python import math result = math.factorial(i) ``` - **参数**:`i` 必须是非负整数(`i >= 0`)。 - **返回值**:`i` 的阶乘(整数类型)。 - **异常**: - 如果 `i` 是负数或浮点数,抛出 `ValueError`。 - 如果 `i` 不是整数(如 `float` 类型),抛出 `TypeError`。 --- ### **示例代码** #### 1. 基本用法 ```python import math print(math.factorial(5)) # 输出: 120 (因为 5! = 5×4×3×2×1 = 120) print(math.factorial(0)) # 输出: 1 (0! 定义为 1) ``` #### 2. 错误处理 ```python try: print(math.factorial(-1)) # 抛出 ValueError except ValueError as e: print("错误:", e) # 输出: factorial() not defined for negative values try: print(math.factorial(3.5)) # 抛出 TypeError except TypeError as e: print("错误:", e) # 输出: 'float' object cannot be interpreted as an integer ``` --- ### **关键特性** 1. **高效性**:`math.factorial` 用 C 语言实现,计算速度远快于纯 Python 实现。 2. **大数支持**:返回的是 Python 的整数类型,可处理任意大的阶乘(受内存限制)。 ```python print(math.factorial(100)) # 输出一个非常大的数(93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000) ``` 3. **数学定义**:`0! = 1`(符合组合数学定义)。 --- ### **应用场景** 1. **组合数学**:计算排列组合数(如 `C(n, k) = factorial(n) // (factorial(k) * factorial(n-k))`)。 2. **概率统计**:二项分布、泊松分布等概率计算。 3. **算法问题**:如生成全排列、解决某些动态规划问题(如爬楼梯问题)。 --- ### **替代实现** 如果需要自定义阶乘(如处理浮点数或负数),可以自行实现: ```python def custom_factorial(i): if not isinstance(i, int) or i < 0: raise ValueError("输入必须是非负整数") result = 1 for j in range(1, i + 1): result *= j return result print(custom_factorial(5)) # 输出: 120 ``` --- ### **性能对比** - `math.factorial` 比递归或循环的 Python 实现快得多: ```python import timeit print(timeit.timeit('math.factorial(100)', setup='import math', number=10000)) # 约 0.001 秒 ``` --- ### **常见问题** 1. **为什么 `math.factorial` 不支持浮点数?** - 阶乘在数学上仅定义在非负整数上。若需扩展到实数,可用 `gamma` 函数(`math.gamma(x + 1)`)。 2. **如何计算大数的阶乘?** - Python 整数自动处理大数,但计算 `factorial(1e6)` 可能耗时较长。 3. **递归实现阶乘的缺陷?** - 递归深度受限(Python 默认递归深度约 1000),且效率低于迭代或 `math.factorial`。 --- ### **扩展:Gamma 函数** 如果需要计算非整数的“阶乘”,可用 `math.gamma`(注意 `gamma(n) = (n-1)!`): ```python import math print(math.gamma(5.5)) # 4.5! ≈ 287.8852778150445 ```
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值