zoukankan      html  css  js  c++  java
  • leetcode:Factorial Trailing Zeroes

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

    Note: Your solution should be in logarithmic time complexity.

    分析:题意即为 阶乘尾部的零(求n!中尾部为0的个数)

    思路:我们可以对n!进行质因数分解有 n!=2x*3y*5z*...,显然尾部0的个数等于min(x,z),并且我们容易知道min(x,z)==z

    因为:阶乘就是1*2*3*...*n
    如果我们用[n/k]表示1~n中能被k整除的个数
    那么很显然
    [n/2] > [n/5] (左边是逢2增1,右边是逢5增1)
    [n/2^2] > [n/5^2](左边是逢4增1,右边是逢25增1)
    ……
    [n/2^p] > [n/5^p](左边是逢2^p增1,右边是逢5^p增1)
    那么可知n!质因数分解中,2的次幂一定大于5的次幂

    于是我们只看n前面有多少个5即可,而n/5就得到了5的个数,还有我们要注意25这种(5和5相乘的结果)

    所以还要看n/5里面有多少个5,相当于看n里面有多少个25,还有125,625.。。

    代码如下:

    class Solution {
    public:
        int trailingZeroes(int n) {
            int count=0;
            while(n){
                count+=n/5;
                n=n/5;
            }
            return count;
        }
    };
    

    或者:

    class Solution {
    public:
        int trailingZeroes(int n) {
        if (n==0) return 0;
        if (n<5 && n>0) return 0;
        int count=0;
        int i=n/5;
        do{
            count+=i;
            i=i/5;
        }  while (i>=1);
        return count;
    }
    };
    

      

      

  • 相关阅读:
    FastDFS集群安装说明
    关于Sentaurus的日常(一)(Basics)
    关于Sentaurus的日常(三)
    记录程序运行时间之clock 函数
    Mysql 使用经验 2013
    proxy ip 收集方式总结
    操作系统的默认格式的陷阱
    VNC server 使用手记
    div body 间距
    asp.net处女作
  • 原文地址:https://www.cnblogs.com/carsonzhu/p/4677525.html
Copyright © 2011-2022 走看看