Math 640:348 Prof. Kontorovich
Spring 2015, 3/27 lecture

We will try to find a prime of size about a million by the Miller-Rabin test

First try numbers of the form

n=2 3 5 7 11 13 j+23

because these are guaranteed to be coprime to 2, 3, 5, 7, 11, and 13, so we have slightly better odds of finding a prime. (This is sometimes called “pre-sieving”.)
Let’s start, say, with

j=200;

so that n is

n

First we write n as 2^k r with r odd.

r=(n-1)/2

We only took out one power of 2, so can only square once.

Now let’s take a random number and test whether it is a witness, say,

a=2;
PowerMod[a,n-1,n]

Aha, so 2 is already a “Fermat witness” for the compositeness of n, and we are now certain that it is not prime.

Try another value of j

j=201;

Then n is

n

Again we compute r, the odd part of n-1

r=(n-1)/2

Nope, take out more 2’s

r=(n-1)/2^2

Ok good, so when we get to the squaring step, we will be able to square twice.

Again let’s try as our first witness

a=2;
PowerMod[a,n-1,n]

And again we immediately find that n is composite, since a^(n-1) is not 1 mod n.

Increment j again

j=202;
n

Now compute r

r=(n-1)/2

So we will only be able to square once (which by Matt’s observation means we don’t need to square at all -- if a^r is not +/-1, then n must be composite). Trying our first witness:

a=2;
PowerMod[a,n-1,n]

Ok, this n might finally be prime. So begin the Miller-Rabin challenge. Raise a to the r mod n:

b=PowerMod[a,r,n]

Looks random at first, but no! That’s just n-1, i.e., -1. Just for fun, let’s square b

b1=PowerMod[b,2,n]

Of course, that’s what it had to come out to. So the value a=2 does not give us a witness for the compositeness of n. With “75% certainty”, n is prime. Let’s try another (more random) value

a=31231;
PowerMod[a,n-1,n]

And compute b

b=PowerMod[a,r,n]

So this value of a is also not a witness. Now we are

N[1-(1/4)^2]

“93% certain” that n is prime. Another random value

a=3121;
PowerMod[a,n-1,n]

b=PowerMod[a,r,n]

With 3 witnesses, we are

N[1-(1/4)^3]

“98% certain” that n is prime. If we tried another 97 witnesses, all of whom failed to force the compositeness of n, we would know that n is prime with “probability”

N[1-(1/4)^100,100]

Indeed,

PrimeQ[n]

and we’ve found our desired large prime.

Now

Change this file and follow along with Example 3.19 on p. 128 in the book, as well as Example 3.22 on p. 130.