next Big Integer - Java java.math

Java examples for java.math:BigInteger

Description

next Big Integer

Demo Code


import java.math.BigInteger;
import java.util.Arrays;
import java.util.Random;

public class Main{
    public static BigInteger nextBigInteger(BigInteger n) {
        return randomBigInteger(rnd, n);
    }//from  www . j a v  a  2s. c  o  m
    /**
     * Computes a random BigInteger that is less than the upper bound BigInteger provided to the method.
     * Since BigInteger doesn't provide a way to generate a random BigInteger in a given range,
     * the method tries to generate a random BigInteger with the same number of bits as the BigInteger provided as an argument. 
     * The method samples these random BigIntegers continuously until one is found that is less than the upper bound BigInteger.
     * @param rnd Random number generator
     * @param n Upper bound BigInteger
     * @return BigInteger that is less than the upper bound BigInteger
     */
    private static BigInteger randomBigInteger(Random rnd, BigInteger n) {
        BigInteger i = null;
        do {
            i = new BigInteger(n.bitLength(), rnd);
        } while (i.compareTo(n) != -1);
        return i;
    }
}

Related Tutorials