Prime Number

Lets write a simple program that will verify if a number is prime number.

public class PrimeNumber {

    @Test
    public void generates_firstPrimeNumber() {
        Assert.assertFalse(isPrimeNumber(BigInteger.valueOf(0)));
        Assert.assertFalse(isPrimeNumber(BigInteger.valueOf(1)));
        Assert.assertTrue(isPrimeNumber(BigInteger.valueOf(2)));
        Assert.assertTrue(isPrimeNumber(BigInteger.valueOf(3)));
        Assert.assertFalse(isPrimeNumber(BigInteger.valueOf(4)));
        Assert.assertTrue(isPrimeNumber(BigInteger.valueOf(5)));
        Assert.assertFalse(isPrimeNumber(BigInteger.valueOf(6)));
    }

    private boolean isPrimeNumber(BigInteger number) {
        if (number.equals(ZERO) || number.equals(ONE)) return false;
        for (BigInteger i = BigInteger.valueOf(2); i.compareTo(number.subtract(ONE)) < 0; i = i.add(ONE)) {
            BigInteger remainder = number.remainder(i);
            if (remainder.equals(ZERO)) return false;
        }
        return true;
    }
}

Now lets try to verify if some big number is a primary number. Lets pick a random number like,

We find that that number is not prime number very quickly. Lets try to add 2 to that number.

Probably, you won't be able to find it in reasonable time. It takes really a lot of time.

Find all prime numbers

If we would keep this algorithm run for few ethernities, we would maybe find the longest prime number so far discovered. This algorithm is the basic version, not optimized and thus very very slow type of algorithm.

What would happen when we run the findAllPrimeNumbers with lests say 999999999999999999999999999999999?

We wouldn't get much far. It takes too much time to find number in single threaded process.

Find prime numbers using multi threaded code

Another logical implication to speed up the search process is to use multiple CPUs to find the prime numbers. Lets say we want to create batches of 100 numbers and use 100 threads to find the numbers. We could write code like this to do it.

Here is a sample output this program produces. You can experiment with size of batch and number of threads if you like this brute force approach.

Be aware, if you are too eager with amount of threads and batch size, you will get this exception.

Last updated

Was this helpful?