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

后端 未结 6 2441
春和景丽
春和景丽 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:31

    Paul suggested in a comment that I generate a number using random bytes, then throw it away if it's too big. Here's what I came up with (Marcel's answer + Paul's advice):

    public static BigInteger RandomIntegerBelow(BigInteger N) {
        byte[] bytes = N.ToByteArray ();
        BigInteger R;
    
        do {
            random.NextBytes (bytes);
            bytes [bytes.Length - 1] &= (byte)0x7F; //force sign bit to positive
            R = new BigInteger (bytes);
        } while (R >= N);
    
        return R;
    }
    

    http://amirshenouda.wordpress.com/2012/06/29/implementing-rsa-c/ helped a little too.

提交回复
热议问题