0

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?

Faris Durrani
  • 87
  • 3
  • 8

1 Answers1

0

Because casting a very large double to 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

Please see the document to find "Narrowing primitive conversions" saying "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."

shoek
  • 380
  • 2
  • 9