首页 > 其他 > 详细

Trailing Zeros

时间:2016-07-06 09:49:56      阅读:252      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!