is Prime Miller Rabin - Java java.lang

Java examples for java.lang:int prime

Description

is Prime Miller Rabin

Demo Code


//package com.java2s;

import static java.lang.Integer.numberOfTrailingZeros;

public class Main {
    public static boolean isPrimeMillerRabin(int n) {
        if (n < 2)
            return false;
        else if (n == 2)
            return true;
        else//from www .jav  a2s. c o m
            return (millerRabinPass(2, n)
                    && (n <= 7 || millerRabinPass(7, n)) && (n <= 61 || millerRabinPass(
                    61, n)));

    }

    private static boolean millerRabinPass(int a, int n) {
        int d = n - 1;
        int s = numberOfTrailingZeros(d);
        d >>= s;

        int a_to_power = modular_exponent(a, d, n);
        if (a_to_power == 1 || a_to_power == n - 1)
            return true;

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

    private static int modular_exponent(int base, int power, int modulus) {
        long result = 1;
        for (int i = 31; i >= 0; i--) {
            result = (result * result) % modulus;
            if ((power & (1 << i)) != 0)
                result = (result * base) % modulus;
        }
        return (int) result;
    }
}

Related Tutorials