java icon indicating copy to clipboard operation
java copied to clipboard

Java prime-factors problems with tests

Open Akrome opened this issue 11 years ago • 5 comments

Aside from test case 0, I get all the tests failing with messages like:

"java.lang.AssertionError: expected: java.util.Arrays$ArrayList<[2, 3]> but was: java.util.ArrayList<[2, 3]>"

The lists match and the values have the same orders. Initially I was using a LinkedList and thought that was the problem, but changing to ArrayList didn't solve the problem.

Oddly enough, test 0 pass (empty list), probably because the initalizer is

Arrays.asList(new Integer[0]);

instead of

Arrays.asList(new Integer[]{})

as the others are.

I'm using IntellijIdea 14.1 , running as JUnit tests. Attached the code for my solver:

public class PrimeFactors {
    public static List<Long> getForNumber(double input) {
        List<Long> result = new ArrayList<>();
        long number = (long) input;

        //Primality checks only up to SQRT(num)
        for (long i = 2; i * i <= input; i++) {
            //Eratosthenes-like approach at removing prime multiples
            while (number > 1 && number % i == 0) {
                number /= i;
                result.add(i);
            }
            //Premature exit if we are done
            if (number <= 1) {
                break;
            }
        }
        //Leftovers are prime numbers too
        if (number > 1) {
            result.add(number);
        }
        return result;
    }
}

Akrome avatar May 11 '15 13:05 Akrome

That's weird (and frustrating).

I think the tests are expecting the type to be Integer not Long Is there a way to write the tests so that it would accept either? It seems to me that the underlying type is not important in this case so long as the code produces the correct results.

kytrinyx avatar May 11 '15 13:05 kytrinyx

The quickest fix I can think of is

assertEquals(expectedOutput -  PrimeFactors.getForNumber(input), 0);

Otherwise we could explicit add casts to long for both sides of the assert.

A bit hacky, but working. Maybe JUnit has something better to offer, though I'm not aware of it.

Akrome avatar May 11 '15 14:05 Akrome

Also, the last test passes in a Long. While its factors are all within the Integer range, it's probably best to just convert the whole test to use all longs?

Akrome avatar May 11 '15 14:05 Akrome

Yeah, let's just use longs everywhere.

Otherwise we could explicit add casts to long for both sides of the assert.

That might not be a bad idea, actually. The downside is it might look like we think it's a good practice, whereas it would probably be best to avoid in the real world.

kytrinyx avatar May 12 '15 06:05 kytrinyx

Given that the last test requires a Long input, I also prefer going with longs everywhere.

Akrome avatar May 12 '15 08:05 Akrome