is Mersenne Prime, Uses the lucas-Lehmer algorithm. 2^n-1 - Java java.lang

Java examples for java.lang:int prime

Description

is Mersenne Prime, Uses the lucas-Lehmer algorithm. 2^n-1

Demo Code


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

public class Main {
    /**/*from w  w  w.  ja  va2  s . co  m*/
     * Uses the lucas-Lehmer algorithm.  2^n-1
     * @param n power of the mersenne prime. 
     * @return true if a mersenne prime
     *         false if it's not a mersenne prime
     */
    public static boolean isMersennePrime(int n) {
        BigInteger s = BigInteger.valueOf(4);
        BigInteger m = BigInteger.valueOf(2).pow(n)
                .subtract(BigInteger.ONE);
        for (int i = 0; i < n - 2; i++)
            s = s.multiply(s).subtract(BigInteger.valueOf(2)).mod(m);

        return s.equals(BigInteger.ZERO);
    }
}

Related Tutorials