So, I'm still new to coding in Java and upon trying ProjectEuler's 29th problem, I tried using the brute-force solution using HashSets but the values stored in the HashSet differs if it is set to store Integer and Double values even if they are always the same values.
ProjectEuler Problem 29: How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?
See below:
// 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();
}
The only difference between the two snippets is HashSet storing either Integer or Double elements. start
and end
are always 2 and 100 respectively. The first method using Double produces 9183 (which is correct) but the second using Integer produces 422 (wrong).
Is there a limiting factor in HashSet's Integer element which it to produce different answers?