Java BigInteger Random mod_rand_with_inverse(Random rand, BigInteger mod)

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

Description

Modular random number generator for the multiplicative subgroup.

License

Open Source License

Parameter

Parameter Description
rand Random number generator
mod modulus

Return

random number less than mod with a modular inverse

Declaration

public static BigInteger mod_rand_with_inverse(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 {
    /**//from  ww  w .  j av  a  2  s  . co m
     * 
     * Modular random number generator for the multiplicative
     * subgroup. Generates an equally disctributed random number less
     * than {@code mod} that has a modular inverse modulo {@code mod}.
     * The bit length of the random number is at most 4 less than
     * {@code mod}.
     * 
     * @param rand Random number generator
     * @param mod modulus
     * @return random number less than {@code mod} with a modular
     * inverse 
     */
    public static BigInteger mod_rand_with_inverse(Random rand, BigInteger mod) {
        BigInteger res;
        do {
            res = mod_rand(rand, mod);
        } while (!coprime(res, mod));
        return res;
    }

    /**
     * 
     * 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;
    }

    /**
     * 
     * Coprime check. Tests whether the two arguments are coprime. Two
     * natural numbers are said to be coprime if the biggest factor
     * they share is 1, ie. if there greatest common divisor is 1.
     * 
     * @param a first BigInteger
     * @param b second BigInteger
     * @return true if {@code a} and {@code b} are coprime.
     */
    public static boolean coprime(BigInteger a, BigInteger b) {
        return a.gcd(b).compareTo(BigInteger.ONE) == 0;
    }
}

Related

  1. mod_rand(Random rand, BigInteger mod)