題目描述
設(shè)計(jì)一個(gè)算法,計(jì)算出n階乘中尾部零的個(gè)數(shù)
思路
n階乘能產(chǎn)生尾數(shù)0,換言之就是問(wèn)n階乘能乘出多少個(gè)10
10分解成兩個(gè)質(zhì)數(shù)相乘就是:2 * 5
考慮 <=n 的數(shù)中,能分解出多少對(duì) 2 && 5
分解的2肯定比5多
問(wèn)題也就轉(zhuǎn)化成了,<=n 的數(shù)中,能分解出多少個(gè)5
n/5 得到能分解出1個(gè)5的個(gè)數(shù)
n/5/5 得到能分解出兩個(gè)5的個(gè)數(shù)
...
所以一個(gè)while循環(huán)就可以搞定
代碼
public long trailingZeros(long n) {
// write your code her
long count = 0;
while(n / 5 != 0) {
n = n / 5;
count += n;
}
return count;
}
考察點(diǎn)
- 數(shù)學(xué)題