Skip to content

Instantly share code, notes, and snippets.

@kabinpokhrel
Last active November 22, 2021 03:49
Show Gist options
  • Save kabinpokhrel/5b7686646697654b4e4de8334ac151f6 to your computer and use it in GitHub Desktop.
Save kabinpokhrel/5b7686646697654b4e4de8334ac151f6 to your computer and use it in GitHub Desktop.
Robin Miller Primality Test
import java.math.BigInteger;
import java.util.Random;
import java.util.Scanner;
public class RobinMillerPrimalityTest {
private static final BigInteger ONE = new BigInteger("1");
private static final BigInteger TWO = new BigInteger("2");
public static void main(String[] args) {
// Initialize the scanner class for user input
Scanner scanner = new Scanner(System.in);
// take the input from the user
System.out.println("Enter the odd number : ");
BigInteger odd = new BigInteger(String.valueOf(scanner.nextInt()));
System.out.println("Enter the security parameter: ");
int securityParameter = scanner.nextInt();
// exponent and odd number
BigInteger oddMinusOne = odd.subtract(ONE);
BigInteger oddMinusTwo = odd.subtract(TWO);
int exponentU = oddMinusOne.getLowestSetBit();
BigInteger oddNumberR = odd.divide(TWO.pow(exponentU));
for (int i = 1; i < securityParameter; i++) {
// Pick a random number a such that {2, ...., oddMinusTwo}
Random rand = new Random();
BigInteger randomA;
do{
randomA = new BigInteger(odd.bitLength(), rand);
}while (randomA.compareTo(oddMinusOne) >= 0 || randomA.compareTo(TWO) == -1);
BigInteger resultPowModulo = randomA.modPow(oddMinusOne, odd);
if (!resultPowModulo.equals(ONE)){
System.out.println("p(tilda) is composite!");
System.exit(0);
}
for (int j = 1; j < exponentU; j++) {
// BigInteger resultModuloDouble = randomA.modPow(oddNumberR.multiply(new BigInteger(String.valueOf(doubleJ))))
if (randomA.modPow(TWO.pow(j).multiply(oddNumberR), odd).equals(ONE) && randomA.modPow(TWO.pow(j).subtract(ONE).multiply(oddNumberR), odd) != ONE){
System.out.println("p(tilda) is composite");
System.exit(0);
}
}
}
System.out.println("p(tilda) is likely a prime");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment