Modular random BigInteger number generator. - Java java.math

Java examples for java.math:BigInteger

Description

Modular random BigInteger number generator.

Demo Code

// This program is free software; you can redistribute it and/or
//package com.java2s;
import java.util.Random;
import java.math.BigInteger;

public class Main {
    /**//from w w  w . j  ava 2s .c  o 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 Tutorials