大量发行 [英] Issue with large number
问题描述
我正在尝试使用阶乘计算尾随零的数量.
I'm trying to count the number of trailing zero with a factorial.
例如
4! = 24所以您检索0.
4! = 24 So you retrieve 0.
9! = 362880因此您检索到1.
9! = 362880 So you retrieve 1.
10! = 9! x 10 = 3628800所以您检索了2.
10! = 9! x 10 = 3628800 So you retrieve 2.
11! = 10! x 11 = 3.99168E7所以您检索了2.
11! = 10! x 11 = 3.99168E7 So you retrieve 2.
static double factorial(double n) {
double f = 1;
for(int i = 1 ; i <= n ; i++) {
f *= i;
}
return f;
}
static int numberOfZeros(double f) {
int ten = 1;
int count = 0;
for(;f%Math.pow(10, ten) == 0;count++) {
ten++;
}
return count;
}
此代码在数字n为22之前是可以的,但是当我尝试将23放入其中时,计数为0. 当然,数学上是23!尾随零.
this codes are Okay until number n is 22. but when i try to put 23 into then count is 0. Of course, mathematically 23! has trailing zeros.
推荐答案
您无需计算阶乘即可计算尾随零.
You don't need to calculate the factorial to count trailing zeroes.
请查看您可以除以5的幂(这是10的较大倍)的多少倍.之所以可行,是因为任何尾随零的数字都可以被10整除.当5出现多次时,您需要执行5的幂才能捕捉到这些时间.
Just see how many times you can divide by powers of 5 (which is the larger factor of 10). This works since any number with a trailing zero will be divisible by 10. You need to do the powers of 5 to catch those times when 5 occurs more than once.
-
for 45! = 45/25 = 1 + 45/5 = 9 = 10 zeroes.
-
for 150! = 150/125 = 1 150/25 = 6, 150/5 = 30 so 1 + 6 + 30 = 37 zeros.
for 45! = 45/25 = 1 + 45/5 = 9 = 10 zeroes.
for 150! = 150/125 = 1 150/25 = 6, 150/5 = 30 so 1 + 6 + 30 = 37 zeros.
现在您要做的就是编写代码.
Now all you have to do is code it.
这篇关于大量发行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!