Codewars --Number of trailing zeros of N!

Number of trailing zeros of N!

Description:

Write a program that will calculate the number of trailing zeros in a factorial of a given number.

N! = 1 * 2 * 3 * 4 ... N


zeros(12) = 2 # 1 * 2 * 3 .. 12 = 479001600
that has 2 trailing zeros 4790016(00)

Be careful 1000! has length of 2568 digital numbers.


来自Codewars上的一个比较初级的题目,但是感觉还是挺有意思的就决定记录下来。


有趣的是最开始由于没有看到最下面的注意事项采用了比较暴力的方法来破解,很快发现这是个错误的方向,因为数字甚至很快就能超过Long的取值范围,改变一下思路发现想要末位是0的话就一定是需要2*5的。由于在公因子中2显然比5更多,所以只要知道5的个数就能够得到末位的0的个数。


其实就是将乘积做因式分解,只是不是对乘积本身而是对每一个乘数。

           for (int i = 1; i <= n; i++) {
                int j=i;
                //因式分解
                while (j%5==0){
                    result++;
                    j=j/5;
                }
            }

另外再贴一个别人的解法,比上面的简洁许多。

public class Solution {
  public static int zeros(int n) {
    int res = 0;
    for (int i = 5; i <= n; i *= 5) {
      res += n / i;
    }
    return res;
  }
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值