Java examples for java.lang:int prime
An deterministic approach to the miller Rabin algorithm, is prime number
//package com.java2s; import java.math.BigInteger; public class Main { /**//from w ww . ja v a 2s .com * An deterministic approach to the miller rabin algorithm * @param n - prime number to test * @return true if prime false if composite */ public static boolean isMillerRabinDeterministic(int n) { if (n < 2) return false; if (n < 9080191) return (isMillerRabin(31, n) && isMillerRabin(73, n)); if (n < 4759123141L) return (isMillerRabin(2, n) && isMillerRabin(7, n) && isMillerRabin( 61, n)); return false; } /** * 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; } }