java使用BigInteger和MillerRabin生成大素数

时间:2014-04-21 16:23:19

标签: java primes

我正在试图弄清楚如何使用java BigInteger生成素数。

我们都知道BigInteger有BigInteger.probablePrime(a,b)。

这很好,但我想用MillerRabin算法检查大数字。下面是我的一段代码:

//method to generate random large number
public static BigInteger rand_bigInt(BigInteger n) {
    Random rand = new Random();
    BigInteger result = new BigInteger(n.bitLength(), rand);
    while( result.compareTo(n) >= 0 ) { 
        result = new BigInteger(n.bitLength(), rand); 
    }
    return result;
}
//method to calculate modular exponentiation
public static BigInteger mod_exp(BigInteger a, BigInteger p, BigInteger m){ 
    BigInteger mod_exp;
    mod_exp = a.modPow(p, m);
    return mod_exp;
}
//method to check the random large number is prime (MillerRabin)
public boolean isPrime(BigInteger n){  
    BigInteger _0 = new BigInteger("0");
    BigInteger _1 = new BigInteger("1");
    BigInteger _2 = new BigInteger("2");

    if(n.compareTo(_0) == 0 || n.compareTo(_1) == 0){ 
        return false;
    }

    if(n.compareTo(_2) == 0){
        return true;
    }

    if(n.remainder(_2).compareTo(_0) == 0){  
        return false;
    }

    BigInteger v = n.subtract(_1);  
    while(v.remainder(_2).compareTo(_0) == 0){  
        v = v.divide(_2);  
    }

    BigInteger j;
    int t = 5;

    for(int i=1; i<=t; i++){
        BigInteger a = rand_bigInt(v);  
        BigInteger y = mod_exp(a, v, n);  

        if(y.compareTo(_1) != 0 && y.compareTo(v) != 0){ 
            j = _1; //j = 1;
            while(j.compareTo(v) <= 0 && y.compareTo(v) != 0){ 
                y = mod_exp(y, _2, n);  
                if(y.compareTo(_1) == 0){  
                    return false;  
                }  
                j = j.add(_1);               
            }  
            if(y.compareTo(v) != 0){  
                return false;  
            }  
        }  
    } 
    return true;
}

然后,我把它放在主要方法中:

BigInteger randomVal = rand_bigInt(new BigInteger("30")); 
Boolean prime = bia.cekPrima(randomVal);
System.out.println("Random: "+randomVal);
System.out.println("Prime? "+ prime);

结果:

Random: 11

Prime? false

结果不是我的预期。

我的代码有什么问题(特别是在MillerRabin方法中)?

我该怎么办才能修复它?

0 个答案:

没有答案