Cracking the coding interview--Q19.3
2014-04-09 16:57
281 查看
题目
原文:
Write an algorithm which computes the number of trailing zeros in n factorial.
译文:
写一个算法计算n的阶乘的尾数的零的个数。
解答
首先,算出n的阶乘的结果再去计算末尾有多少个0这种方法是不可取的, 因为n的阶乘是一个非常大的数,分分种就会溢出。我们应当去分析, 是什么使n的阶乘结果末尾出现0。
n阶乘末尾的0来自因子5和2相乘,5*2=10。因此,我们只需要计算n的阶乘里, 有多少对5和2。注意到2出现的频率比5多,因此,我们只需要计算有多少个因子5即可。 我们可以列举一些例子,看看需要注意些什么:
给定一个n,用n除以5,得到的是从1到n中包含1个5的数的个数;然后用n除以5去更新n, 相当于把每一个包含5的数中的因子5取出来一个。然后继续同样的操作,让n除以5, 将得到此时仍包含有5的数的个数,依次类推。最后把计算出来的个数相加即可。 比如计算25的阶乘中末尾有几个0, 先用25除以5得到5,表示我们从5,10,15,20,25中各拿一个因子5出来,总共拿了5个。 更新n=25/5=5,再用n除以5得到1,表示我们从25中拿出另一个因子5, 其它的在第一次除以5后就不再包含因子5了。
代码如下:
转自:http://hawstein.com/posts/19.3.html
---EOF---
原文:
Write an algorithm which computes the number of trailing zeros in n factorial.
译文:
写一个算法计算n的阶乘的尾数的零的个数。
解答
首先,算出n的阶乘的结果再去计算末尾有多少个0这种方法是不可取的, 因为n的阶乘是一个非常大的数,分分种就会溢出。我们应当去分析, 是什么使n的阶乘结果末尾出现0。
n阶乘末尾的0来自因子5和2相乘,5*2=10。因此,我们只需要计算n的阶乘里, 有多少对5和2。注意到2出现的频率比5多,因此,我们只需要计算有多少个因子5即可。 我们可以列举一些例子,看看需要注意些什么:
5!, 包含1*5, 1个5 10!, 包含1*5,2*5, 2个5 15!, 包含1*5,2*5,3*5, 3个5 20!, 包含1*5,2*5,3*5,4*5, 4个5 25!, 包含1*5,2*5,3*5,4*5,5*5, 6个5 ...
给定一个n,用n除以5,得到的是从1到n中包含1个5的数的个数;然后用n除以5去更新n, 相当于把每一个包含5的数中的因子5取出来一个。然后继续同样的操作,让n除以5, 将得到此时仍包含有5的数的个数,依次类推。最后把计算出来的个数相加即可。 比如计算25的阶乘中末尾有几个0, 先用25除以5得到5,表示我们从5,10,15,20,25中各拿一个因子5出来,总共拿了5个。 更新n=25/5=5,再用n除以5得到1,表示我们从25中拿出另一个因子5, 其它的在第一次除以5后就不再包含因子5了。
代码如下:
int NumZeros(int n){ if(n < 0) return -1; int num = 0; while((n /= 5) > 0){ num += n; } return num; }
转自:http://hawstein.com/posts/19.3.html
---EOF---
相关文章推荐
- 《Cracking the Coding Interview》——第8章:面向对象设计——题目1
- 《Cracking the Coding Interview》——第13章:C和C++——题目3
- 《Cracking the Coding Interview》——第14章:Java——题目5
- 《Cracking the Coding Interview》——第16章:线程与锁——题目6
- 《Cracking the Coding Interview》——第17章:普通题——题目14
- Cracking the Coding Interview 150题(二)
- Cracking the coding interview: 查找文中两个单词的距离
- Cracking the Coding Interview 8.5
- Cracking the Coding Interview(Trees and Graphs)
- Cracking the coding interview--Q8.8
- Cracking the coding interview--Q2.4
- Cracking the coding interview--Q5.5
- { Cracking The Coding Interview: 150 programming Q&A } 5th edition Part I
- Cracking the coding interview--Q8.5
- Cracking the coding interview--Q1.3
- Cracking the coding interview Q1.1
- Cracking the coding interview(中文版)
- Cracking the coding interview--Q11.1~Q11.6
- 《Cracking the Coding Interview》——第2章:链表——题目5
- 《Cracking the Coding Interview》——第3章:栈和队列——题目7