Java BigInteger Random mod_rand(Random rand, BigInteger mod)

Here you can find the source of mod_rand(Random rand, BigInteger mod)

Description

Modular random number generator.

License

Open Source License

Parameter

Parameter Description
rand Random number generator
mod modulus

Return

a random number less than mod

Declaration

public static BigInteger mod_rand(Random rand, BigInteger mod) 

Method Source Code


//package com.java2s;
// modify it under the terms of the GNU General Public License as

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

public class Main {
    /**// ww  w. ja v a 2s . co  m
     * 
     * Modular random number generator. Generate an equally
     * distributed random number less than {@code mod} with a bit
     * length at most 4 less than the bit length of {@code mod}.
     * 
     * @param rand Random number generator
     * @param mod modulus
     * @return a random number less than {@code mod}
     */
    public static BigInteger mod_rand(Random rand, BigInteger mod) {
        int bit_size = mod.bitLength();
        BigInteger res;
        do {
            res = new BigInteger(bit_size, rand);
        } while (res.bitLength() < bit_size - 4 || res.compareTo(mod) >= 0);
        return res;
    }
}

Related

  1. mod_rand_with_inverse(Random rand, BigInteger mod)