Java Code Examples for java.math.BigInteger#nextProbablePrime()

The following examples show how to use java.math.BigInteger#nextProbablePrime() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Add a local primes cache, to save some time for primes computation
 *
 * @param n the requested size of the list
 * @throws NotEnoughPrimesInGroupException if the encryption group is too small to yield the requested number of $
 *                                         primes
 */
public synchronized void populatePrimesCache(int n) throws NotEnoughPrimesInGroupException {
    Preconditions.checkState(cachedPrimes == null, "The primes cache can only be initialized" +
            "once...");
    BigInteger x = BigInteger.ONE;
    ImmutableList.Builder<BigInteger> cacheBuilder = ImmutableList.builder();
    int i = 0;
    while (i < n) {
        do {
            // Performance improvement over +1 / +2 defined in algorithm
            x = x.nextProbablePrime();
            if (x.compareTo(encryptionGroup.getP()) >= 0)
                throw new NotEnoughPrimesInGroupException(
                        String.format("Only found %d primes (%s) in group %s",
                                i,
                                Joiner.on(",").join(
                                        cacheBuilder.build().stream().limit(4)
                                                .collect(Collectors.toList())), encryptionGroup));
        } while (!x.isProbablePrime(100) || !isMember(x));
        cacheBuilder.add(x);
        i++;
    }

    cachedPrimes = cacheBuilder.build();
}
 
Example 2
/**
	 * Verify that the corrected lower/upper integers of sqrt(N) are computed.
	 */
	@SuppressWarnings("unused")
	private static void testCorrectness() {
		for (int nBits = 20; ; nBits+=10) {
			LOG.info("Test correctness of " + NCOUNT + " N with " + nBits + " bits:");
			int i = 0;
			while (i < NCOUNT) {
				BigInteger n = new BigInteger(nBits, RNG);
				if (n.equals(I_0)) continue; // exclude 0 from test set
				
				// supposed correct value:
				BigInteger nextProbablePrime = n.nextProbablePrime();
				
				// check others
				try {
					BigInteger nextProbablePrime_bpsw = bpsw.nextProbablePrime(n);
//					assertEquals(nextProbablePrime, nextProbablePrime_bpsw);
				} catch (AssertionError ae) {
					LOG.error("Failure at n=" + n + ": " + ae, ae);
				}
				i++;
			}
			LOG.info("    Tested " + NCOUNT + " next probable primes...");
		}
	}
 
Example 3
Source Project: j2objc   File: OldBigIntegerTest.java    License: Apache License 2.0 5 votes vote down vote up
static void largePrimesProduct(BigInteger a, BigInteger b, String c) {
        BigInteger wp = a.multiply(b);
        assertFalse("isProbablePrime failed for product of two large primes" +
                        a + " * " + b + " = " + c,
                wp.isProbablePrime(80) );
        BigInteger wpMinusOne = wp.subtract(BigInteger.ONE);
        BigInteger next = wpMinusOne.nextProbablePrime();
//        System.out.println(c);
//        System.out.println(next);
        assertTrue("nextProbablePrime returns wrong number: " + next +
                        "instead of expected: " + c,
                next.toString().equals(c) );
    }
 
Example 4
/**
 * @param N
 * @return first prime > N
 */
public BigInteger nextProbablePrime(BigInteger N) {
	// Java's built-in function using a sieve to identify prime candidates is stronger for N>=256 bit.
	if (N.bitLength()>=256) return N.nextProbablePrime();
	
    N = N.abs(); // sign is irrelevant
    if (N.bitLength()<=1) return I_2;
	// skip argument and make even argument odd
    N = N.testBit(0) ? N.add(I_2) : N.add(I_1);
	
	// loop to next prime
	while (!isProbablePrime(N)) N = N.add(I_2);
	return N;
}
 
Example 5
/**
 * @param N
 * @return first prime > N
 */
public BigInteger nextProbablePrime(BigInteger N) {
	// Java's built-in function using a sieve to identify prime candidates is stronger for N>=256 bit.
	if (N.bitLength()>=256) return N.nextProbablePrime();
	
    N = N.abs(); // sign is irrelevant
    if (N.bitLength()<=1) return I_2;
	// skip argument and make even argument odd
    N = N.testBit(0) ? N.add(I_2) : N.add(I_1);
	
	// loop to next prime
	while (!isProbablePrime(N)) N = N.add(I_2);
	return N;
}
 
Example 6
Source Project: RipplePower   File: IntegerPolynomial.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Multithreaded version of {@link #resultant()}.
 *
 * @return <code>(rho, res)</code> satisfying <code>res = rho*this + t*(x^n-1)</code> for some integer <code>t</code>.
 */
public Resultant resultantMultiThread()
{
    int N = coeffs.length;

    // upper bound for resultant(f, g) = ||f, 2||^deg(g) * ||g, 2||^deg(f) = squaresum(f)^(N/2) * 2^(deg(f)/2) because g(x)=x^N-1
    // see http://jondalon.mathematik.uni-osnabrueck.de/staff/phpages/brunsw/CompAlg.pdf chapter 3
    BigInteger max = squareSum().pow((N + 1) / 2);
    max = max.multiply(BigInteger.valueOf(2).pow((degree() + 1) / 2));
    BigInteger max2 = max.multiply(BigInteger.valueOf(2));

    // compute resultants modulo prime numbers
    BigInteger prime = BigInteger.valueOf(10000);
    BigInteger pProd = Constants.BIGINT_ONE;
    LinkedBlockingQueue<Future<ModularResultant>> resultantTasks = new LinkedBlockingQueue<Future<ModularResultant>>();
    Iterator<BigInteger> primes = BIGINT_PRIMES.iterator();
    ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    while (pProd.compareTo(max2) < 0)
    {
        if (primes.hasNext())
        {
            prime = primes.next();
        }
        else
        {
            prime = prime.nextProbablePrime();
        }
        Future<ModularResultant> task = executor.submit(new ModResultantTask(prime.intValue()));
        resultantTasks.add(task);
        pProd = pProd.multiply(prime);
    }

    // Combine modular resultants to obtain the resultant.
    // For efficiency, first combine all pairs of small resultants to bigger resultants,
    // then combine pairs of those, etc. until only one is left.
    ModularResultant overallResultant = null;
    while (!resultantTasks.isEmpty())
    {
        try
        {
            Future<ModularResultant> modRes1 = resultantTasks.take();
            Future<ModularResultant> modRes2 = resultantTasks.poll();
            if (modRes2 == null)
            {
                // modRes1 is the only one left
                overallResultant = modRes1.get();
                break;
            }
            Future<ModularResultant> newTask = executor.submit(new CombineTask(modRes1.get(), modRes2.get()));
            resultantTasks.add(newTask);
        }
        catch (Exception e)
        {
            throw new IllegalStateException(e.toString());
        }
    }
    executor.shutdown();
    BigInteger res = overallResultant.res;
    BigIntPolynomial rhoP = overallResultant.rho;

    BigInteger pProd2 = pProd.divide(BigInteger.valueOf(2));
    BigInteger pProd2n = pProd2.negate();

    if (res.compareTo(pProd2) > 0)
    {
        res = res.subtract(pProd);
    }
    if (res.compareTo(pProd2n) < 0)
    {
        res = res.add(pProd);
    }

    for (int i = 0; i < N; i++)
    {
        BigInteger c = rhoP.coeffs[i];
        if (c.compareTo(pProd2) > 0)
        {
            rhoP.coeffs[i] = c.subtract(pProd);
        }
        if (c.compareTo(pProd2n) < 0)
        {
            rhoP.coeffs[i] = c.add(pProd);
        }
    }

    return new Resultant(rhoP, res);
}
 
Example 7
@Override
public IExpr evaluate(final IAST ast, EvalEngine engine) {
	IExpr arg1 = ast.arg1();
	if (arg1.isNegative() || arg1.isOne() || arg1.isZero()) {
		return F.C0;
	}

	IExpr x = F.NIL;
	if (arg1.isInteger()) {
		x = arg1;
	} else if (arg1.isReal() && arg1.isPositive()) {
		x = engine.evaluate(((ISignedNumber) arg1).floorFraction());
	} else {
		ISignedNumber sn = arg1.evalReal();
		if (sn != null) {
			x = engine.evaluate(sn.floorFraction());
		}
	}

	if (x.isInteger() && x.isPositive()) {
		// TODO improve performance by caching some values?

		int maxK = ((IInteger) x).toIntDefault(Integer.MIN_VALUE);
		if (maxK >= 0) {
			int result = 0;
			BigInteger max = BigInteger.valueOf(maxK);
			BigInteger temp = BigInteger.ONE;
			int iterationLimit = engine.getIterationLimit();
			if (iterationLimit >= 0 && iterationLimit < (maxK / 100)) {
				IterationLimitExceeded.throwIt(maxK, ast);
			}
			for (int i = 2; i <= maxK; i++) {
				temp = temp.nextProbablePrime();
				if (temp.compareTo(max) > 0) {
					break;
				}
				result++;
			}
			return F.ZZ(result);
		}
	}

	return F.NIL;
}
 
Example 8
Source Project: ripple-lib-java   File: IntegerPolynomial.java    License: ISC License 4 votes vote down vote up
/**
 * Multithreaded version of {@link #resultant()}.
 *
 * @return <code>(rho, res)</code> satisfying <code>res = rho*this + t*(x^n-1)</code> for some integer <code>t</code>.
 */
public Resultant resultantMultiThread()
{
    int N = coeffs.length;

    // upper bound for resultant(f, g) = ||f, 2||^deg(g) * ||g, 2||^deg(f) = squaresum(f)^(N/2) * 2^(deg(f)/2) because g(x)=x^N-1
    // see http://jondalon.mathematik.uni-osnabrueck.de/staff/phpages/brunsw/CompAlg.pdf chapter 3
    BigInteger max = squareSum().pow((N + 1) / 2);
    max = max.multiply(BigInteger.valueOf(2).pow((degree() + 1) / 2));
    BigInteger max2 = max.multiply(BigInteger.valueOf(2));

    // compute resultants modulo prime numbers
    BigInteger prime = BigInteger.valueOf(10000);
    BigInteger pProd = Constants.BIGINT_ONE;
    LinkedBlockingQueue<Future<ModularResultant>> resultantTasks = new LinkedBlockingQueue<Future<ModularResultant>>();
    Iterator<BigInteger> primes = BIGINT_PRIMES.iterator();
    ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    while (pProd.compareTo(max2) < 0)
    {
        if (primes.hasNext())
        {
            prime = primes.next();
        }
        else
        {
            prime = prime.nextProbablePrime();
        }
        Future<ModularResultant> task = executor.submit(new ModResultantTask(prime.intValue()));
        resultantTasks.add(task);
        pProd = pProd.multiply(prime);
    }

    // Combine modular resultants to obtain the resultant.
    // For efficiency, first combine all pairs of small resultants to bigger resultants,
    // then combine pairs of those, etc. until only one is left.
    ModularResultant overallResultant = null;
    while (!resultantTasks.isEmpty())
    {
        try
        {
            Future<ModularResultant> modRes1 = resultantTasks.take();
            Future<ModularResultant> modRes2 = resultantTasks.poll();
            if (modRes2 == null)
            {
                // modRes1 is the only one left
                overallResultant = modRes1.get();
                break;
            }
            Future<ModularResultant> newTask = executor.submit(new CombineTask(modRes1.get(), modRes2.get()));
            resultantTasks.add(newTask);
        }
        catch (Exception e)
        {
            throw new IllegalStateException(e.toString());
        }
    }
    executor.shutdown();
    BigInteger res = overallResultant.res;
    BigIntPolynomial rhoP = overallResultant.rho;

    BigInteger pProd2 = pProd.divide(BigInteger.valueOf(2));
    BigInteger pProd2n = pProd2.negate();

    if (res.compareTo(pProd2) > 0)
    {
        res = res.subtract(pProd);
    }
    if (res.compareTo(pProd2n) < 0)
    {
        res = res.add(pProd);
    }

    for (int i = 0; i < N; i++)
    {
        BigInteger c = rhoP.coeffs[i];
        if (c.compareTo(pProd2) > 0)
        {
            rhoP.coeffs[i] = c.subtract(pProd);
        }
        if (c.compareTo(pProd2n) < 0)
        {
            rhoP.coeffs[i] = c.add(pProd);
        }
    }

    return new Resultant(rhoP, res);
}