To find a prime, you don't need to test every numbers below it up to it's square root; you simply need to test every other prime below it. Here's a demo :
ArrayList<Integer> primes = new ArrayList<Integer>(); // hold every other prime numbers that we find
boolean isPrime;
// add first base prime number
primes.add(2);
for (int x = 3; x < max; x+=2) { // start from 3 and skip multiples of 2
isPrime = true; // prove it's not prime
for (Integer i : primes) {
if (x % i == 0) {
isPrime = false; // x is divisible by a prime number...
break; // exit loop, we proved it's not a prime
}
}
if (isPrime) {
if (x >= 10) {
System.out.println(x); // print only two digits prime numbers
}
primes.add(x); // add x to our prime our number list for future checks
}
}
** EDIT **
A yet more flexible and reusable implementation in a static method (not optimized for listing large prime numbers) :
public static List<Integer> findPrimes(int min, int max) {
LinkedList<Integer> primes = new LinkedList<Integer>();
boolean isPrime;
double square;
// add first base prime number
primes.add(2);
for (int x = 3; x < max; x+=2) { // start from 3 and skip multiples of 2
isPrime = true; // prove it's not prime
square = Math.sqrt(x);
for (Integer i : primes) {
isPrime = x % i != 0; // x is not prime if it is divisible by i
if (!isPrime || i > square) {
break;
}
}
if (isPrime) {
primes.add(x); // add x to our prime numbers
}
}
// remove all numbers below min
while (!primes.isEmpty() && primes.getFirst() < min) {
primes.removeFirst();
}
return primes;
}
Method usage :
List<Integer> primes = findPrimes(10, 100);
System.out.println("Listing " + primes.size() + " prime numbers");
for (Integer prime : primes) {
System.out.println(prime);
}