# Determine whether a number is prime

How do I determine if a number is prime? I'm writing a program where a user inputs any integer and from that the program determines whether the number is prime, but how do I go about that?

-

4
If you down vote my question please let me know why so that I can improve my question asking in the future. – KronoS Sep 24 '10 at 15:55
I had accidentally down-voted the question it appears... fixed now – jericson Sep 28 '10 at 23:41
@jericson no prob just wanted to make the question better. – KronoS Sep 29 '10 at 0:16

1
– mixedmath♦ Sep 5 '11 at 3:01
@mixedmath: what is your rationale for voting to close this qustion instead of the one you link to? – t.b. Sep 7 '11 at 16:51
show 1 more comment

## 5 Answers

Have the program find the remainder when dividing the input (say n) by 2, 3, 4, ..., $\sqrt n$ (or the following integer if $\sqrt n$ is not an integer.) If this value ever leaves a remainder of zero then your number is composite and you can stop checking divisors. If the remainder is non-zero for all of these values then your number is prime.

There are more efficient ways to check primeness but this is probably the easiest way to program it and I imagine will suffice for your purposes. Unless you are checking very very large numbers?

-

2
Of course, once you check 2 you don't need to check any multiples of 2, and the same for 3 etc. But if you just want a simple algorithm and space/time constraints aren't an issue then what I wrote above would be very easy to program and would be fine for not too huge inputs. – jericson Sep 23 '10 at 5:42
This is exactly what I was looking for. Not doing any crazy large numbers. – KronoS Sep 24 '10 at 2:42

1
You don't need to check the following integer if $\sqrt{n}$ is not integral, you can stop just before it. If you store a list of primes, just divide by those up to $\sqrt{n}$ – Ross Millikan Sep 5 '11 at 3:52
@RossMillikan: I think this is a guard against rounding errors. If you compute $\sqrt{p^2}$ as a little bit less than $p$ due to round-off you would mischaracterize $p^2$ as composite, but not if you checked to the next integer. – Charles Apr 8 at 15:28

How do I mathematically determine if a number is prime?

If the number is n, then dividing it by every prime number less than or equal to sqrt(n) and showing that there is a remainder.

There are a number of different sieve solutions for finding prime numbers, the oldest and most famous of which is the Sieve of Eratosthenes. These are generally easy to programme and can, for example, find all of the primes below 100,000 in a few milliseconds on a modern processor.

-

Algorithm posted by jericson is the best for basic purposes.

IMHO, for programming competitions and for practical purposes randomized algorithms are best. Rabin-Miller is my favorite.

Take a look at Rabin-Miller primality testing algorithm code @ TopCoder.

As primes are in P, there is deterministic, polynomial time algorithm called AKS primality test.

-

2
Calling the Miller-Rabin algorithm a “nondeterministic algorithm” is technically correct but misleading (in the same way as calling a rectangle a parallelogram). It is a randomized algorithm. – Tsuyoshi Ito Sep 23 '10 at 12:36
@Tsuyoshi Ito: Changed. Thanks! :) – Pratik Deoghare Sep 23 '10 at 12:53

1
It's worth mentioning that the efficient versions of AKS are no longer deterministic. – Charles Sep 27 '10 at 14:54

1
@Sri: That's actually the funny thing about AKS; thus, it remains more a curiosity than a practical test. – J. M. Sep 5 '11 at 2:57

1
@Srivatsan Narayanan: Glad to help. It's exciting times we're seeing! When the test first came out it was hard to imagine an efficient version, but thanks to improvements on the exponent (starting from the work of Berrizbeitia) and amazing millionfold improvements to the constant factor (due to Bernstein) the algorithm looks usable if not yet competitive. – Charles Sep 5 '11 at 3:56
show 3 more comments

There are many different algorithms for primality testing. See the Wikipedia page for an introduction and see Henri Cohen's book "A course in computational algebraic number theory" for further details. See also Caldwell's Prime Pages.

-

For very small numbers (less than a million), trial division is the best way: divide by 2, 3, 5, and so on until the square root of the number. If you find a factor, the number is composite; otherwise, the number is prime.

For larger numbers there are better methods, but choosing which one depends on how much work you're willing to put into the program. It is now known that there are no BPSW-pseudoprimes below $2^{64}$, so if you can write that test (see here for details) then you have a very quick test for primality.

If you only need to test up to $2^{32}$, you can simply check if the number is a 2-strong pseudoprime. If so, test if it's one of 2314 exceptions (this can be done in 12 or 13 steps with a binary search); if the test fails or it's an exception, the number is composite, otherwise prime. (You can go higher than $2^{32}$ if you're willing to build an appropriate table of exceptions.)

For larger numbers, the work is usually split into two parts: determining with high probability (say, 99.99999999%) that the number is prime, then actually proving that it is. What type of proof depends on the form and size of the number.

-

4
Nice answer. Very informative! – jericson Sep 23 '10 at 5:43

4
This is definitely the best answer overall. – KronoS Sep 24 '10 at 2:43
@Charles you said "divide by 2, 3, 5, and so on until the square root of the number." Why is it sufficient to do check upto the square root of the number and why divide by only primes ? – Geek Aug 14 '12 at 4:59
A composite number is always divisible by a prime number <= its square root. You can think of it this way: if you find a composite proper factor, either that has a prime factor <= its square root (which will divide the original number) or it has a composite factor <= its square root (in which case iterate). It can't have factors onlly larger than its square root since you could take one and divide the number by it to find one smaller than the square root. The process of taking smaller and smaller composite factors can't continue forever since there can be at most n steps. – Charles Aug 14 '12 at 12:15
{"extraction_info": {"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 10, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0}, "config": {"markdown_headings": true, "markdown_code": true, "boilerplate_config": {"ratio_threshold": 0.18, "absolute_threshold": 10, "end_threshold": 15, "enable": true}, "remove_buttons": true, "remove_image_figures": true, "remove_link_clusters": true, "table_config": {"min_rows": 2, "min_cols": 3, "format": "github"}, "remove_chinese": true, "remove_edit_buttons": true, "extract_latex": true}, "english_confidence": 0.9148827791213989, "perplexity_flag": "middle"}