- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
这是我编写的两个版本的代码,用于返回 n! 中尾随零的数量。第一个版本为输入 1808548329
返回 452137080
,第二个版本为输入 1808548329
返回 452137076
。想知道为什么会有差异?第二个版本的输出是正确的。
Java源代码,
public class TrailingZero {
public static int trailingZeroes(int n) {
int result = 0;
int base = 5;
while (n/base > 0) {
result += n/base;
base *= 5;
}
return result;
}
public static int trailingZeroesV2(int n) {
return n == 0 ? 0 : n / 5 + trailingZeroesV2(n / 5);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(trailingZeroes(1808548329));
System.out.println(trailingZeroesV2(1808548329));
}
}
最佳答案
这是由于 integer overflow在 base
的值中。
稍微更改您的代码以打印 n/base
和 base
:
public class TrailingZero {
public static int trailingZeroes(int n) {
int result = 0;
int base = 5;
while (n/base > 0) {
System.out.println("n = " + n/base + " base = " + base);
result += n/base;
base *= 5;
}
return result;
}
public static int trailingZeroesV2(int n) {
return n == 0 ? 0 : n / 5 + trailingZeroesV2(n / 5);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(trailingZeroes(1808548329));
System.out.println(trailingZeroesV2(1808548329));
}
}
输出:
n = 361709665 base = 5
n = 72341933 base = 25
n = 14468386 base = 125
n = 2893677 base = 625
n = 578735 base = 3125
n = 115747 base = 15625
n = 23149 base = 78125
n = 4629 base = 390625
n = 925 base = 1953125
n = 185 base = 9765625
n = 37 base = 48828125
n = 7 base = 244140625
n = 1 base = 1220703125
n = 1 base = 1808548329 <== OOPS 6103515625 overflows 32-bit integer
n = 3 base = 452807053
452137080
正如您在此处看到的,当 n =
1 时,base
增加到 1220703125
。然后语句 base *= 5
运行,这使得 6103515625
超过最大 32 位无符号整数 (2^32
) 6103515625 - 2^32 = 1808548329
,这就是您在上面看到的 b
的中间错误值(OOPS
)。
另一方面,递归解决方案仅使用不断减小的n
的值。因此没有溢出。
简单的解决方案是将 base
声明为 long,即 long base = 5
。这将返回 452137076
的正确值。
另一种解决方案是将循环修改为仅使用 n
,类似于递归解决方案:
int base = 5;
while (n > 0) {
result += n/base;
n = n/base;
}
请注意,在涉及阶乘的问题中,溢出是给定的,您可能需要考虑更高精度的算术,例如 BigInteger .
关于java - 查找阶乘尾随零时的结果不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42756140/
我正在做一些关于大 O 表示法的练习题,遇到了这个问题。什么是函数 𝑓(𝑛) = 𝑛^2 + 𝑛 log2(𝑛) + log2(𝑛) 的大 O 阶。展示你的作品。 我的答案是 O(n^2)
是2n吗?只是检查。 最佳答案 术语 B 树的顺序在文献中的定义并不一致。 (例如,参见 terminology section of Wikipedia's article on B-Trees )
我想使用 numpy 创建一个 3 列数组,使得该数组类似于一堆 9x9 2 列数组。这些数组中的每一个都将完全填充有 1、2、3 等。 所以,看立方体的一面,我们看到的是 1,而另一面则是 9。然后
我想将这些数据存储到顺序为 3 (10,20,30,40,50,60,70,80,90) 的 B 树中,我的结果是 并且它与我的书的结果不匹配。可以吗?谢谢:) 最佳答案 这取决于你的意思 Is it
我是 numpy 的新手。创建一个新数组并用一定范围内的随机数填充每个元素的最佳方法是什么? 例如,我想要一个 3×3 数组,其中每个元素都是 0 或 1。 最佳答案 尝试类似的东西 np.rando
我正在尝试学习设计 btree。 以下是开发 5 阶 btree 的值。 1,12,8,2,25,6,14,28,17,7,52,16,48,68,3,26,29,53,55,45,67。 当我插入
我有一个 pandas 数据框,其特征值非常小,数量级为 -322。我正在尝试标准化这些功能,但得到了 ValueError: Input contains NaN, infinity or a va
我是一名优秀的程序员,十分优秀!