zoukankan      html  css  js  c++  java
  • LeetCode(172)Factorial Trailing Zeroes

    题目

    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,求对于n!末尾0的个数。

    开始看到的时候并没有什么思路,只知道n!=123...n

    那么末尾0是怎么产生的呢,必然是 质因数 25而导致的结果 , 又搜索了网上一些资料:

    对n!做质因数分解n!=2x3y5z...

    显然0的个数等于min(x,z),并且min(x,z)==z

    证明:

    对于阶乘而言,也就是123...n
    [n/k]代表1n中能被k整除的个数
    那么很显然
    [n/2]>[n/5](左边是逢2增1,右边是逢5增1)
    [n/22]>[n/52](左边是逢4增1,右边是逢25增1)
    ……
    [n/2p]>[n/5p](左边是逢2p增1,右边是逢5p增1)
    随着幂次p的上升,出现2p的概率会远大于出现5p的概率。
    因此左边的加和一定大于右边的加和,也就是n!质因数分解中,2的次幂一定大于5的次幂

    此时,便很明了了,结果可以表示为:
    n!后缀0的个数 = n!质因子中5的个数 = floor(n/5)+floor(n/25)+floor(n/125)+....

    AC代码

    class Solution {
    public:
        int trailingZeroes(int n) {
            int count = 0;
            while (n)
            {
                count += n / 5;
                n /= 5;
            }
            return count;
        }
    };
  • 相关阅读:
    什么是Portal!
    Maven 让事情变得简单
    HTTP协议详解
    函数实现不放在头文件的原因,及何时可以放头文件的情况
    Linux中的内存管理(四)Heap
    寿星万年历Lua实现
    TCP epoll触发后只accept一次带来的问题
    生产者消费者问题
    Windows SDK 实现不规则窗口
    论迭代式的产品开发方法
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214759.html
Copyright © 2011-2022 走看看