HashSet 不以相同的方式存储相等的 Integer 和 Double 值
HashSet not storing equal Integer and Double values the same way
所以,我对 Java 中的编码还是个新手,在尝试使用 ProjectEuler 的 29th problem 时,我尝试使用 HashSet 的暴力解决方案,但存储在 HashSet 中的值会有所不同设置为存储 Integer 和 Double 值,即使它们始终是相同的值。
ProjectEuler Problem 29: How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?
见下文:
// Java
private static int distinctAb(int start, int last) {
HashSet<Double> products = new HashSet<>();
for (int a = start; a <= last; a++) {
for (int b = start; b <= last; b++) {
double result = Math.pow(a, b);
products.add(result);
}
}
return products.size();
}
private static int distinctAbInt(int start, int last) {
HashSet<Integer> products = new HashSet<>();
for (int a = start; a <= last; a++) {
for (int b = start; b <= last; b++) {
double result = Math.pow(a, b);
products.add((int) result);
}
}
return products.size();
}
这两个片段之间的唯一区别是 HashSet 存储 Integer 或 Double 元素。 start
和 end
总是分别为 2 和 100。使用 Double 的第一种方法产生 9183(正确),但使用 Integer 的第二种方法产生 422(错误)。
HashSet 的 Integer 元素是否存在产生不同答案的限制因素?
因为将非常大的 double
转换为 int
returns Integer.MAX_VALUE
.
System.out.println((int) Math.pow(99,100)); // Prints 2147483647
System.out.println((int) Math.pow(100,100)); // Prints 2147483647
请参阅 the document 找到 "Narrowing primitive conversions" 说 "The value must be too large (a positive value of large magnitude or positive infinity), and the result of the first step is the largest representable value of type int or long."
所以,我对 Java 中的编码还是个新手,在尝试使用 ProjectEuler 的 29th problem 时,我尝试使用 HashSet 的暴力解决方案,但存储在 HashSet 中的值会有所不同设置为存储 Integer 和 Double 值,即使它们始终是相同的值。
ProjectEuler Problem 29: How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?
见下文:
// Java
private static int distinctAb(int start, int last) {
HashSet<Double> products = new HashSet<>();
for (int a = start; a <= last; a++) {
for (int b = start; b <= last; b++) {
double result = Math.pow(a, b);
products.add(result);
}
}
return products.size();
}
private static int distinctAbInt(int start, int last) {
HashSet<Integer> products = new HashSet<>();
for (int a = start; a <= last; a++) {
for (int b = start; b <= last; b++) {
double result = Math.pow(a, b);
products.add((int) result);
}
}
return products.size();
}
这两个片段之间的唯一区别是 HashSet 存储 Integer 或 Double 元素。 start
和 end
总是分别为 2 和 100。使用 Double 的第一种方法产生 9183(正确),但使用 Integer 的第二种方法产生 422(错误)。
HashSet 的 Integer 元素是否存在产生不同答案的限制因素?
因为将非常大的 double
转换为 int
returns Integer.MAX_VALUE
.
System.out.println((int) Math.pow(99,100)); // Prints 2147483647
System.out.println((int) Math.pow(100,100)); // Prints 2147483647
请参阅 the document 找到 "Narrowing primitive conversions" 说 "The value must be too large (a positive value of large magnitude or positive infinity), and the result of the first step is the largest representable value of type int or long."