Implementation of the Miller-Rabin algorithm, prime number. - Java java.lang

Java examples for java.lang:int prime

Description

Implementation of the Miller-Rabin algorithm, prime number.

Demo Code


//package com.java2s;
import java.math.BigInteger;

public class Main {
    /**//from w w w  .jav a2s . c o  m
     * Implementation of the Miller-Rabin algorithm. 
     * WARNING : This does not return the correct results all the time.
     *           Results depend on the base used. If you still want to utilize
     *           the speed of the Miller-Rabin algorithm with known working
     *           base numbers, use isMillerRabinDeterministic(). 
     * @return true:  if prime (not always true)
     *         false: if composite (always true)
     */
    public static boolean isMillerRabin(long a, long n) {
        long d = n - 1;
        long s = Long.numberOfTrailingZeros(d);
        d >>= s;

        long aPow = modPow(a, d, n);
        if (aPow == 1 || aPow == n - 1)
            return true;

        for (int i = 0; i < s - 1; i++) {
            aPow = modPow(aPow, 2, n);
            if (aPow == n - 1)
                return true;
        }
        return false;
    }

    private static final long modPow(long i, long j, long k) {
        if (k > Integer.MAX_VALUE) {
            BigInteger x = BigInteger.valueOf(i);
            BigInteger y = BigInteger.valueOf(j);
            BigInteger z = BigInteger.valueOf(k);
            return x.modPow(y, z).longValue();
        }
        i %= k;
        if (j == 2)
            return i * i % k;
        long val = 1;
        while (j > 0) {
            if ((j & 1) != 0)
                val = val * i % k;
            i = i * i % k;
            j >>= 1;
        }
        return val;
    }
}

Related Tutorials