This code example shows how to calculate and find prime numbers. It has an int variable called UPPER_LIMIT which tells the program for how long it will keep on looking and calculating.

Since it’s not possible to divide a prime value with any other number (except for itself and one) and receive an integer without rounding,

we try to divide every number we find with smaller numbers. To avoid making too many calculations we can first calculate the square root of each number and then use that for the division.

If a modulus calculation of all of the numbers below that square root number produces a result that is not equal to zero, then we have found a prime number.

There are an endless number of prime numbers but in this program we use integers which means that we can only find prime numbers up to Integer.MAX_VALUE.

To find larger numbers we need other numeric types.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
/** * * @author www.javadb.com */ public class Main { private final int UPPER_LIMIT = 10000; public void calculatePrimeNumbers() { int i = 0; int primeNumberCounter = 0; while (++i <= UPPER_LIMIT) { int i1 = (int) Math.ceil(Math.sqrt(i)); boolean isPrimeNumber = false; while (i1 > 1) { if ((i != i1) && (i % i1 == 0)) { isPrimeNumber = false; break; } else if (!isPrimeNumber) { isPrimeNumber = true; } --i1; } if (isPrimeNumber) { System.out.println(i); ++primeNumberCounter; } } System.out.println("Nr of prime numbers found: " + primeNumberCounter); } /** * @param args the command line arguments */ public static void main(String[] args) { new Main().calculatePrimeNumbers(); } } |

The result when running the program looks something like this:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
2 3 5 7 11 13 17 19 23 29 ... ... ... 9907 9923 9929 9931 9941 9949 9967 9973 |

Search for more Java info on this site here: