I recently was part of a small java programming competition at my school. My partner and I have just finished our first pure oop class and most of the questions were out of
The big inefficiency here is your prime testing method prime. Take a think about the number of times it will have to test the very same numbers, and concentrate on how one might take advantage of memory structures in order to avoid some of the repeated calculations.
Even faster than all of that is using the Miller-Rabin test. It's a probabilistic test, and therefore has a certain level of error; however, the test runs multiple times which shrinks that error as small as needed (50 often suffices for commercial applications).
Not in Java, but here's a quick implementation in Python I cooked up.
@David get the square root of a number and then loop till square root eliminate even numbers and see if it is not divisble
@outis...i see what you are saying thats a neat little trick i must say. thank you for that.
@Graham...also cool i read an article on the test you mentioned because although I think i understood the gist of it from the comments you made Python always looks like greek to me. I know everyone says its one of the simpler languages to pick up but for whatever reason java and c++ always look more readable to me. Anyway, yea that wouldve been a much better way to do it. Thanks again to all of you who gave me tips I learned alot from this board. Can't for my data structures and algorithms class in the fall!!!
Using BigInteger.isProbablePrime(certainty) and BigInteger.nextProbablePrime() can significantly cut down the number of cases you need to check quite efficiently