zoukankan      html  css  js  c++  java
  • [LeetCode]66. Factorial Trailing Zeros阶乘的尾零个数

    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.

    Subscribe to see which companies asked this question

     
    解法1:如果N! == K×10M, ( 0 != k%10 ),那么M就是要求的。我们把N!进行质因数分解,则有 N! == 2* 3Y * 5Z……,而10是怎么来的呢,分解之后不就只能由2×5来。也就是说,只要求分解后的min(x, z),又显然,分解之后2的个数显然要比5的个数多。所以,M == Z。根据分析,要计算 Z,最直接的方法,就是计算i(i =1, 2, …, N)的因式分解中5 的指数,然后求和。
    class Solution {
    public:
        int trailingZeroes(int n) {
            int cnt = 0, j;
            for (int i = 5; i <= n; i += 5) {
                int j = i;
                while (j % 5 == 0) {
                    ++cnt;
                    j /= 5;
                }
            }
            return cnt;
        }
    };

    这种解法会在N超大时超时Time Limit Exceeded。题目的Note要求我们写出对数时间复杂度的解法。

    解法2:在解法1的基础上考虑到能贡献5的数全是5的倍数,而5的指数(5,25,125,...)能贡献5的个数恰好是幂的值(1,2,3,...),非5的指数(10,15,20,30,,...)则只能贡献一个5。而使用N除以5可以得到在[1,N]中有多少个5的倍数,除以25可以得到有多少个25的倍数……这样所有的结果加起来恰好可以算出[1,N]中一共有多少个5。注意25=5*5即可以贡献两个5,而在前面除以5的时候已经计算过一次了,所以加1次就可以了,同理125=5*5*5,在2和25的时候已经考虑到两个5了,所以后面也是再加一个就行了,后面所有5的指数都如此。

    class Solution {
    public:
        int trailingZeroes(int n) {
            int cnt = 0;
            long long k = 5;
            while(k <= n) {
                cnt += n / k;
                k *= 5;
            }
            return cnt;
        }
    };

    注意k必须定义为long long类型以防止在n极大时k会溢出。一个避免这个陷阱的写法如下:

    class Solution {
    public:
        int trailingZeroes(int n) {
            int cnt = 0;
            while(n > 0) {
                cnt += n / 5;
                n /= 5;
            }
            return cnt;
        }
    };
  • 相关阅读:
    p2psearcher绿色版使用方法
    P2PSearcher云点播设置和使用技巧
    怎么看电脑有没有安装USB3.0驱动
    USB3.0驱动与2.0有什么区别
    win7 64位 安装java jdk1.8 ,修改配置环境变量
    jdk是什么?jdk1.8安装配置方法
    adb工具包究竟能帮我们做什么?
    web.xml中load-on-startup有和用处
    Spring Aop
    Struts2中的properties文件详解
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/4949015.html
Copyright © 2011-2022 走看看