First, let's talk about the Rabin-Miller algorithm for detecting prime numbers,
There are a lot of algorithm descriptions on the Internet, so there are errors due to repeated reprinting. The following is what I got after combining multiple modifications.
// Rabin-Miller
// This is a simple algorithm that is easy to use and widely used. It is developed based on part of Gary Miller's image method with Michael Rabin. In fact, this is a simplified version of the algorithms recommended in nist dss recommendations.
// First select a random number P for the test generation, and calculate the number of times B and B is the sum of 2 and 1. Then calculate m so that p = 1 + (2 ^ B) M.
// (1) Select a random number a smaller than P and greater than 2.
// (2) Set J = 0 and Z = a ^ m mod p
// (3) if z = 1 or Z = p-1, then P passes the test and may make the prime number
// (4) if j> 0 and Z = 1, P is not a prime number.
// (5) set J = J + 1. If j <B and z <P-1, set Z = Z ^ 2 mod P and return to (4 ). If Z is p, p passes the test and may be a prime number.
// (6) if J = B and z <P-1, it is not a prime number.
// The probability that number A is treated as evidence is 75%. This means that when the number of iterations is t, it takes no more than 1/4 ^ t to generate a false prime number.
// In fact, for most random numbers, almost 99.99% certainly a is evidence.
/* Rabin-Miller */<br/> Public static Boolean rabinmiller (INT p) <br/> {<br/> // select a random number P for testing, calculate the number of times that B and B are divided by 2 to 1. Then calculate m so that p = 1 + (2 ^ B) m, that is, M = (p-1)/(2 ^ B ), and M is an odd number <br/> int B = 0, M = p-1; // according to the formula p = 1 + (2 ^ B) m, B = 0 m = p-1 which is used as the initial value to calculate an odd number of M; <br/> while (M % 2 = 0) <br/> {<br/> // every time M is divided into 2, B must be added once. According to the formula p = 1 + (2 ^ B) m, finally, we can obtain an odd number of M <br/> M/= 2; <br/> B ++; <br/>}</P> <p> // (1) select a random number a less than P and greater than 2. <Br/> random = new random (); <br/> int A = random. next (3, P-1); </P> <p> // (2) set J = 0 and Z = a ^ m mod P <br/> Int J = 0; <br/> int z = (INT) math. pow (a, m) % P; </P> <p> // (3) if z = 1 or Z = p-1, then P passes the test, possible prime number <br/> If (Z = 1 | z = (p-1) <br/>{< br/> return true; <br/>}</P> <p> // (4) if j> 0 and Z = 1, P is not a prime number. <br/> // (5) set J = J + 1. If j <B and z <P-1, set Z = Z ^ 2 mod P and return to (4 ). If Z is p, p passes the test and may be a prime number. <Br/> // (6) if J = B and z <P-1, it is not a prime number <br/> while (+ j <= B) <br/>{< br/> If (Z = p-1) <br/>{< br/> return true; <br/>}< br/> Z = (INT) math. pow (z, 2) % P; <br/>}< br/> return false; <br/>}