Java BigInteger is Prime isBigPrime(BigInteger number)

Here you can find the source of isBigPrime(BigInteger number)

Description

is Big Prime

License

Open Source License

Declaration

public static boolean isBigPrime(BigInteger number) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010 liXiaopeng. All rights reserved. 
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 *
 * Contributors://from www .  j  a  v a 2  s  .c om
 *     LiXiaopeng - initial API and implementation
 *
 * Create on 2011-3-7 ????03:28:18
 *******************************************************************************/

import java.math.BigInteger;

import java.util.Random;

public class Main {

    public static boolean isBigPrime(BigInteger number) {

        BigInteger random = createRandomInteger(number, new Random());

        return testPrime(number, random);
    }

    public static boolean isBigPrime(BigInteger number, int agains) {

        BigInteger[] randoms = new BigInteger[agains];
        Random r = new Random();

        for (int index = 0; index < agains; index++) {
            randoms[index] = createRandomInteger(number, r);
        }

        for (BigInteger bi : randoms) {
            if (!testPrime(number, bi)) {
                return false;
            }
        }
        return true;
    }

    private static BigInteger createRandomInteger(BigInteger number,
            Random random) {

        BigInteger result = new BigInteger(number.bitLength(), random);
        if (result.compareTo(number) >= 0) {
            result = result.divide(BigInteger.valueOf(2));
        }

        if (result.compareTo(BigInteger.valueOf(0)) == 0) {
            result = BigInteger.valueOf(1);
        }
        return result;
    }

    private static boolean testPrime(BigInteger number, BigInteger random) {

        System.out.println(random.intValue());

        BigInteger result = random.modPow(
                number.add(BigInteger.valueOf(-1)), number);

        System.out.println(result.intValue());

        return result.intValue() == 1;
    }
}

Related

  1. calculateMPrime(BigInteger n, byte[] message)
  2. fnvHash(final byte[] data, final BigInteger fnvOffs, final BigInteger fnvPrime, final BigInteger mod)
  3. hasSqrtModPrime(BigInteger r, BigInteger p)
  4. isCoprime(BigInteger a, BigInteger b)
  5. isFermatPrime(BigInteger f)
  6. isPrime(BigInteger value)
  7. primeProcessPart(BigInteger from)