How can I generate a random BigInteger within a certain range?

后端 未结 6 2409
春和景丽
春和景丽 2021-02-13 06:52

Consider this method that works well:

public static bool mightBePrime(int N) {
    BigInteger a = rGen.Next (1, N-1);
    return modExp (a, N - 1, N) == 1;
}
         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-13 07:35

    The following Range method will return an IEnumerable within the range you specify. A simple Extension method will return a random element within the IEnumerable.

    public static IEnumerable Range(BigInteger from, BigInteger to)
    {
        for(BigInteger i = from; i < to; i++) yield return i;
    }
    
    public static class Extensions
    {
        public static BigInteger RandomElement(this IEnumerable enumerable, Random rand)
        {
            int index = rand.Next(0, enumerable.Count());
            return enumerable.ElementAt(index);
        }
    }
    

    usage:

    Random rnd = new Random();
    var big = Range(new BigInteger(10000000000000000), new BigInteger(10000000000000020)).RandomElement(rnd);
    

    // returns random values and in this case it was 10000000000000003

提交回复
热议问题