码迷,mamicode.com
首页 > 其他好文 > 详细

Trailing Zeros

时间:2016-07-06 09:50:44      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

Write an algorithm which computes the number of trailing zeros in n factorial.

Example

11! = 39916800, so the out should be 2

 1 class Solution {
 2     /*
 3      * param n: As desciption
 4      * return: An integer, denote the number of trailing zeros in n!
 5      我们会发现: the number of 2s in prime factors is always more than or equal 
 6      to the number of 5s. So if we count 5s in prime factors, we are done. 
 7 
 8     How to count total number of 5s in prime factors of n!? A simple way is 
 9     to calculate floor(n/5). 
10 
11     问题转化为求阶乘过程中质因子5的个数,但是要注意25能提供2个5,125能提供3个5....
12     所以,count= floor(n/5) + floor(n/25) + floor(n/125) + ....
13      */
14 public long trailingZeros(long n) {
15         if (n < 0) return 0;
16 
17         long total = 0;
18         long base = 5;
19         while (base <= n) {
20             total += n / base;
21             base *= 5;
22         }
23         return total;
24     }
25 };

 

Trailing Zeros

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5645567.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!