Well, one thing you can do is that you don't have to check all numbers from 2 to n - 1 for being a divisor of n. It's enough to check those up to sqrt(n). So you can rewrite your checkNumber function like this:
- boolean checkNumber(int n) {
- for (int i = 2; i <= Math.sqrt(n); i++) {
- if (n % i == 0) {
- return false;
- }
- }
- return true;
- }
Also note that since return exits a function immediately, there is no need for first breaking out of the loop, etc. Using that modification, the applet shows up over here almost immediately for dim = 200 and after a second or two for dim = 500.
Another thing you can do: Take advantage of the fact that you're not only checking a single number, but a whole range. To see whether a number is prime, you only need to check whether any of the
prime numbers below divides it. So you can remember all the prime numbers you found before, and check only against these. For example like this:
- int max = 10000;
- int[] primes = new int[max]; // This is too big, but OK for a demo :)
- int primeIndex = 0;
- for (int i = 2; i < max; i++) {
- boolean isPrime = true;
- for (int j = 0; j < primeIndex; j++) {
- if (i % primes[j] == 0) {
- isPrime = false;
- break;
- }
- }
- if (isPrime) {
- println(i + " is a prime number!");
- primes[primeIndex] = i;
- primeIndex++;
- }
- }
And the last thing: Simply remember that the number of primality checks you have to do grows quadratically with dim: At some point, it is just a whole lot of numbers

There are
far more advanced algorithms for primality checks, but I doubt it would be worth the effort in your case (these algorithms are developped for really large numbers featuring hundreds of digits).