Java examples for java.util:Random
Modular random number generator for the multiplicative subgroup.
// 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 . jav a2 s . com * * 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; } }