LeetCode172—Factorial Trailing Zeroes

逃离我推掉我的手 2022-07-14 01:47 501阅读 0赞

原题

原题链接

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

Note: Your solution should be in logarithmic time complexity.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

分析

这个题求n!后面尾随了多少个0?

思路1

能产生0的方式,最小公因数分别是2和5,已知n!=n⋅(n−1)⋅(n−2)…2⋅1,这里面至少能提供n2个因数2,因此产生0的重任就在5身上了,关键是看从[5,n]这个范围内,能够贡献出多少个因数5。

  1. class Solution {
  2. public:
  3. int trailingZeroes(int n) {
  4. int count = 0;
  5. for(long i=5;i<=n;i+=5)
  6. {
  7. long j = i;
  8. while(0==j%5)
  9. {
  10. ++count;
  11. j/=5;
  12. }
  13. }
  14. return count;
  15. }
  16. };

LeetCode提交这个代码,超时。

思路2

能不能再简化呢?总之我们是求因数5的个数,那么这5的来源可以是数字5,贡献1个5,数字25贡献两个5,数字30贡献1个5。

对于一个数字n来说,⌊n5⌋ 表示[1,n]有多少个能被5整除的数,同理⌊n25⌋表示多少个能被25整除。因此:
对于求序列中5的因数个数来说,即求[1,n]有多少个数能被5整除,能被25整除,能被125整除…
[1,n]中能被5整除的所有数分别贡献1个5,[1,n]中所有能被25整除的数分别再贡献1个5…

  1. lass Solution {
  2. public:
  3. int trailingZeroes(int n) {
  4. int count = 0;
  5. while (n)
  6. {
  7. count += n/5;
  8. n/=5;
  9. }
  10. return count;
  11. }
  12. };

发表评论

表情:
评论列表 (有 0 条评论,501人围观)

还没有评论,来说两句吧...

相关阅读