In your primes
function you:
- Check if the current number is divisible by two
- Check to see if it's prime
- Create an array to put your output in.
- Check every number in the range again for primality before putting it in your array.
The problem is in the last step. By double-checking whether each number is prime, you're duplicating your most expensive operations.
You could use a dynamic data structure and add prime numbers to it as you find them. That way you only need to check once.
Alternatively, you could create a boolean array which is the size of your input range. Then as you find primes, set the corresponding array value to true.
UPDATE:
There are still a number of improvements you can make, but some will require more work than others to implement. Look at the specifics of your test and see what fits your needs.
Low-hanging fruit:
- Use an
ArrayList
to collect primes as you find them inprimes
, as opposed to looping over the values twice. - In
closestPrime
, you're checking every single value on either side ofnum
: half of these are even, thus not prime. You could adapt your code to check only odd numbers for primality.
Trickier to implement:
- Try a more advanced algorithm for
IsPrime
: check out the Sieve of Eratosthenes
Above all, you should spend some time figuring out exactly where the bottlenecks are in your code. Oftentimes performance problems are caused by code we thought was perfectly fine. You might consider looking into the code-profiling options available in your development environment.