27.Factorial Trailing Zeroes(求n!有几个0)

来源:互联网 发布:网络修真小说排行榜 编辑:程序博客网 时间:2024/06/02 21:28

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

Note: Your solution should be in logarithmic time complexity.

分析:

阶乘末尾一个零表示一个进位,则相当于乘以10  而10 是由2*5所得,在1~n当中,可以产生10的有:0 2 4 5 6 8 结尾的数字,  显然2是足够的,因为4、6、8当中都含有因子2,所以都可看当是2,那么关键在于5的数量了  那么该问题的实质是要求出1~n含有多少个5  由特殊推广到一般的论证过程可得:

  1、 每隔5个,会产生一个0,比如 5, 10 ,15,20.

       2 、每隔 5×5 个会多产生出一个0,比如 25,50,75,100 
       3、每隔 5×5×5 会多出一个0,比如125.

例如求1000!中有几个0;

      1000/5=200; 200/5=40; 40/5=8; 8/5=1; 1/5=0。

      则1000的阶乘末尾0的个数为:200+40+8+1=249。

public int trailingZeroes(int n) {int total = 0;while(n/5!=0){total += n/5;n=n/5;}return total;            }

0 0
原创粉丝点击