Dav*_*kim 2 java math largenumber factorial java-8
我正在尝试用阶乘计算尾随零的数量。
例如
4!= 24 所以你检索到 0。
9!= 362880 所以你检索 1。
10!= 9!x 10 = 3628800 所以你检索 2。
11!= 10!x 11 = 3.99168E7 所以你检索 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;
}
Run Code Online (Sandbox Code Playgroud)
这个代码是好的,直到数字 n 是 22。但是当我尝试将 23 放入然后计数是 0。当然,数学上是 23!有尾随零。
您不需要计算阶乘来计算尾随零。
看看你可以除以 5 的幂(这是 10 的较大因数)的次数。这是有效的,因为任何带有尾随零的数字都可以被 10 整除。您需要使用 5 的幂来捕捉 5 多次出现的时间。
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.现在你要做的就是编码。
| 归档时间: |
|
| 查看次数: |
120 次 |
| 最近记录: |