public class Divisor extends Thread { //Will hold the number to be tested private int testNumber; //Will hold the number we will try to divide by private AtomicInteger nextNumber; private int sqrtOfTestNumber; public Divisor(AtomicInteger nextNumber, int testNumber) { this.nextNumber = nextNumber; this.testNumber = testNumber; sqrtOfTestNumber = (int) Math.ceil(Math.sqrt(testNumber)); } @Override public void run() { while (nextNumber.intValue() < sqrtOfTestNumber && PrimeTester.IS_PRIME.get()) { if (testNumber % nextNumber.incrementAndGet() == 0) { PrimeTester.IS_PRIME.set(false); System.out.println(testNumber + " is not a prime!"); System.out.println("It can be divided by " + nextNumber.intValue() + "."); return; } } } }
public class PrimeTester { public static AtomicBoolean IS_PRIME = new AtomicBoolean(true); private AtomicInteger nextNumber = new AtomicInteger(1); private int numberOfThreads; private int testNumber; public PrimeTester(int numberOfThreads, int testNumber) { this.numberOfThreads = numberOfThreads; this.testNumber = testNumber; } public void test() { for (int i = 0; i < numberOfThreads; i++) { new Divisor(nextNumber, testNumber).start(); } } public static void main(String[] args) { PrimeTester primeTester = new PrimeTester(5, 370248452); primeTester.test(); } }
Note that the program will not output anything if the number is prime. This is because additional checks have to be performed in order to do this and it will complicate the code. Since this is meant to be a simple example, it has not been included here. Maybe it can be explained in a future post.