a variation of the classic Miller-Rabin test in that it makes the function deterministic. - Java java.lang

Java examples for java.lang:int prime

Description

a variation of the classic Miller-Rabin test in that it makes the function deterministic.

Demo Code


//package com.java2s;

import java.math.BigInteger;
import java.security.SecureRandom;

public class Main {
    /** Convienence variable for the BigInteger Zero */
    private static BigInteger ZERO_INT = new BigInteger("0");
    /** Convienence variable for the BigInteger One */
    private static BigInteger ONE_INT = new BigInteger("1");
    /** Convienence variable for the BigInteger Two */
    private static BigInteger TWO_INT = new BigInteger("2");

    /**/*from w ww. j  a v  a 2 s .co  m*/
     * <p>
     * This function is a variation of the classic Miller-Rabin test in that it
     * makes the function deterministic. This is done by not chosing random
     * numbers but by working our way through all numbers from 2 to 2*ln(n)^2.
     * </p>
     * <a href="http://en.wikipedia.org/wiki/Miller-Rabin_test">
     * http://en.wikipedia.org/wiki/Miller-Rabin_test
     * </a>
     * @param n
     *            The number in question
     * @return true if the number is prime for all witnesses
     */
    public static boolean checkMRD(BigInteger n) {
        boolean rval = true;

        SecureRandom srnd = new SecureRandom();
        BigInteger r = n.subtract(ONE_INT);
        BigInteger s = ZERO_INT;
        BigInteger a = ZERO_INT;
        BigInteger y = ZERO_INT;

        while (r.mod(TWO_INT).compareTo(ZERO_INT) == 0) {
            r = r.divide(TWO_INT);
            s = s.add(ONE_INT);
        }

        BigInteger t = new BigInteger(n.bitLength() + "");
        t = t.pow(2);
        t = t.multiply(TWO_INT);
        for (BigInteger i = TWO_INT; i.compareTo(t) < 1 && rval; i = i
                .add(ONE_INT)) {
            a = i;
            y = a.modPow(r, n);
            if (y.compareTo(ONE_INT) != 0
                    && (y.compareTo(n.subtract(ONE_INT)) != 0)) {
                BigInteger j = ONE_INT;
                while (j.compareTo(s.subtract(ONE_INT)) <= 0
                        && y.compareTo(n.subtract(ONE_INT)) != 0 && rval) {
                    y = y.modPow(TWO_INT, n);
                    if (y.compareTo(ONE_INT) == 0) {
                        rval = false;
                    }
                    j = j.add(ONE_INT);
                }
                if (y.compareTo(n.subtract(ONE_INT)) != 0) {
                    rval = false;
                }
            }
        }
        return rval;
    }
}

Related Tutorials