public static BigInteger Random(this Random generator, BigInteger limit) { ContractUtils.Requires(limit.Sign >= 0, "limit"); ContractUtils.RequiresNotNull(generator, "generator"); // TODO: this doesn't yield a uniform distribution (small numbers will be picked more frequently): byte[] bytes = new byte[limit.GetByteCount() + 1]; generator.NextBytes(bytes); bytes[bytes.Length - 1] = 0; return new BigInteger(new BigInt(bytes)) % limit; }