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.

The result when running the program looks something like this:







Search for more Java info on this site here:
Custom Search


Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">