您的位置:首页 > 大数据 > 人工智能

02 Number of trailing zeros of N!(求N的阶乘末尾0的数目)

2016-11-19 17:03 190 查看

题目描述

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.

分析

最后一句话告诉我们1000!有2568个数字,所以你把结果算出来然后再得出来末尾0的数目是不可能的.所以还是要动下脑子的.不要总是暴力方式解决问题.

注意到两点:只有2*5可以成为末尾0,而且乘法具有交换律,所以我们将能因式分解出2和5的乘数都因式分解,min(count(2),count(5))便为我们所求的答案了,然而显然count(2)要比count(5)要多得多,所以只需要求出count(5)就可以了,所以问题就简化成求count(5)

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


over
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  codewars