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

Factorial Trailing Zeroes

时间:2015-01-16 16:25:27      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

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

Note: Your solution should be in logarithmic time complexity.

 

最初想法是计算里面能被5整除的数字的个数(因为能被2整除的肯定多于5). 后来发现不对,要将所有数字包含的最大5的阶乘数加起来。 (即25的话要算2)

n!后缀0的个数 = n!质因子中5的个数
              = floor(n/5) + floor(n/25) + floor(n/125) + ....
 1 public class Solution {
 2     public int trailingZeroes(int n) {
 3         int result = 0;
 4         // for(int i = 1; i <= n; i ++){
 5         //     int cur = i;
 6         //     while(cur % 5 == 0){
 7         //         cur /= 5;
 8         //         result ++;
 9         //     }
10         // }
11         for(long i = 5; i <= n; i *=5){
12             result += (int)n / i;
13         }
14         return result;
15     }
16 }

 

Factorial Trailing Zeroes

标签:

原文地址:http://www.cnblogs.com/reynold-lei/p/4228781.html

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