Computes a random BigInteger that is less than the upper bound BigInteger provided to the method. - Java java.lang

Java examples for java.lang:Math Calculation

Description

Computes a random BigInteger that is less than the upper bound BigInteger provided to the method.

Demo Code


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

import java.util.Random;

public class Main {
    /**//from w ww.  java 2 s .  c om
     * 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