%mathpiper,def="IsPrime",categories="User Functions;Number Theory"

2 # IsPrime(_n)_(Not IsInteger(n) Or n<=1) <-- False;
3 # IsPrime(n_IsInteger)_(n<=FastIsPrime(0)) <-- IsSmallPrime(n);

/* Fast pseudoprime testing: if n is a prime, then 24 divides (n^2-1) */
5 # IsPrime(n_IsPositiveInteger)_(n > 4 And Modulo(n^2-1,24)!=0) <-- False;

/* Determine if a number is prime, using Rabin-Miller primality
   testing. Code submitted by Christian Obrecht
 */
10 # IsPrime(n_IsPositiveInteger) <-- RabinMiller(n);

%/mathpiper



%mathpiper_docs,name="IsPrime",categories="User Functions;Number Theory;Predicates"
*CMD IsPrime --- test for a prime number
*CMD IsSmallPrime --- test for a (small) prime number
*STD
*CALL
	IsPrime(n)
	IsSmallPrime(n)

*PARMS

{n} -- integer to test

*DESC

The commands checks whether $n$, which should be a positive integer,
is a prime number. A number $n$ is a prime number if it is only divisible
by 1 and itself. As a special case, 1 is not considered a prime number.
The first prime numbers are 2, 3, 5, ...

The function {IsShortPrime} only works for numbers $n<=65537$ but it is very fast.

The function {IsPrime} operates on all numbers and uses different algorithms depending on the magnitude of the number $n$.
For small numbers $n<=65537$, a constant-time table lookup is performed.
(The function {IsShortPrime} is used for that.)
For numbers $n$ between $65537$ and $34155071728321$, the function uses the Rabin-Miller test together with table lookups to guarantee correct results.

For even larger numbers a version of the probabilistic Rabin-Miller test is executed.
The test can sometimes mistakenly mark a number as prime while it is in fact composite, but a prime number will never be mistakenly declared composite.
The parameters of the test are such that the probability for a false result is less than $10^(-24)$.

*E.G.

In> IsPrime(1)
Result: False;
In> IsPrime(2)
Result: True;
In> IsPrime(10)
Result: False;
In> IsPrime(23)
Result: True;
In> Select(1 .. 100, "IsPrime")
Result: {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,
	  53,59,61,67,71,73,79,83,89,97};

*SEE IsPrimePower, Factors
%/mathpiper_docs