172. Factorial Trailing Zeroes计算n!末尾0的个数
2017-07-06 12:07
381 查看
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
题目描述:给定一个整数n,返回n!(n的阶乘)数字中的后缀0的个数。
考虑n!的质数因子。后缀0总是由质因子2和质因子5相乘得来的,如果我们可以计数2和5个数,问题就解决了。
考虑例子:n = 5时,5!的质因子中(2 * 2 * 2 * 3 * 5)包含一个5和三个2。因而后缀0的个数是1。
n = 11时,11!的质因子中((2 ^ 8) * (3 ^ 4) * (5 ^ 2) * 7)包含两个5和八个2。于是后缀0的个数就是2。
我们很容易观察到质因子中2的个数总是大于等于5的个数,因此只要计数5的个数即可。
那么怎样计算n!的质因子中所有5的个数呢?一个简单的方法是计算floor(n / 5)。例如,7!有一个5,10!有两个5。
除此之外,还有一件事情要考虑。诸如25,125之类的数字有不止一个5。
例如n=25, n!=25*24*23*…15…*10…*5…*1=(5*5)*24*23…(5*3)…(5*2)…(5*1)…*1,其中25可看成5*5,多了一个5,应该加上
处理这个问题也很简单,首先对n÷5,移除所有的单个5,然后÷25,移除额外的5,以此类推。下面是归纳出的计算后缀0的公式。
n!后缀0的个数 = n!质因子中5的个数= floor(n / 5) + floor(n / 25) + floor(n / 125) + ….
Note: Your solution should be in logarithmic time complexity.
题目描述:给定一个整数n,返回n!(n的阶乘)数字中的后缀0的个数。
考虑n!的质数因子。后缀0总是由质因子2和质因子5相乘得来的,如果我们可以计数2和5个数,问题就解决了。
考虑例子:n = 5时,5!的质因子中(2 * 2 * 2 * 3 * 5)包含一个5和三个2。因而后缀0的个数是1。
n = 11时,11!的质因子中((2 ^ 8) * (3 ^ 4) * (5 ^ 2) * 7)包含两个5和八个2。于是后缀0的个数就是2。
我们很容易观察到质因子中2的个数总是大于等于5的个数,因此只要计数5的个数即可。
那么怎样计算n!的质因子中所有5的个数呢?一个简单的方法是计算floor(n / 5)。例如,7!有一个5,10!有两个5。
除此之外,还有一件事情要考虑。诸如25,125之类的数字有不止一个5。
例如n=25, n!=25*24*23*…15…*10…*5…*1=(5*5)*24*23…(5*3)…(5*2)…(5*1)…*1,其中25可看成5*5,多了一个5,应该加上
处理这个问题也很简单,首先对n÷5,移除所有的单个5,然后÷25,移除额外的5,以此类推。下面是归纳出的计算后缀0的公式。
n!后缀0的个数 = n!质因子中5的个数= floor(n / 5) + floor(n / 25) + floor(n / 125) + ….
class Solution{ public: int trailingzeros(int n){ int res=0; while(n) { res=res+n/5; n=n/5; } return res; } };
相关文章推荐
- Java 计算N阶乘末尾0的个数-LeetCode 172 Factorial Trailing Zeroes
- 172. Factorial Trailing Zeroes (计算n的阶乘尾部有多少个零)
- [LeetCode] 172. Factorial Trailing Zeroes 求阶乘末尾零的个数
- LeetCode 172. Factorial Trailing Zeroes (阶乘末尾零的数量)
- 172. Factorial Trailing Zeroes -- 求n的阶乘末尾有几个0
- 172. Factorial Trailing Zeroes
- 172. Factorial Trailing Zeroes
- Leetcode#172. Factorial Trailing Zeroes
- 172. Factorial Trailing Zeroes详细解答
- [Leetcode] 172. Factorial Trailing Zeroes 解题报告
- LeetCode 172. Factorial Trailing Zeroes
- leetcode 172. Factorial Trailing Zeroes
- 【一天一道LeetCode】#172. Factorial Trailing Zeroes
- 172. Factorial Trailing Zeroes
- LeetCode 172. Factorial Trailing Zeroes(0结尾)
- 172. Factorial Trailing Zeroes
- [Leetcode]172. Factorial Trailing Zeroes
- leetcode No172. Factorial Trailing Zeroes
- 172. Factorial Trailing Zeroes
- Leetcode 172. Factorial Trailing Zeroes