How to find and calculate prime numbers


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.


/**
 *
 * @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:

2
3
5
7
11
13
17
19
23
29

...
...
...

9907
9923
9929
9931
9941
9949
9967
9973

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: