您对特定BigInteger构造函数的使用是合理的,但您应该使用rejection method来选择一个fermat基底a。以下是对类中的一个轻微修改,该类也只使用一个Random对象:
import java.math.BigInteger;
import java.util.Random;
public class FermatTestExample
{
private final static Random rand = new Random();
private static BigInteger getRandomFermatBase(BigInteger n)
{
// Rejection method: ask for a random integer but reject it if it isn't
// in the acceptable set.
while (true)
{
final BigInteger a = new BigInteger (n.bitLength(), rand);
// must have 1 <= a < n
if (BigInteger.ONE.compareTo(a) <= 0 && a.compareTo(n) < 0)
{
return a;
}
}
}
public static boolean checkPrime(BigInteger n, int maxIterations)
{
if (n.equals(BigInteger.ONE))
return false;
for (int i = 0; i < maxIterations; i++)
{
BigInteger a = getRandomFermatBase(n);
a = a.modPow(n.subtract(BigInteger.ONE), n);
if (!a.equals(BigInteger.ONE))
return false;
}
return true;
}
public static void main(String[] args)
{
System.out.printf("checkprime(2) is %b%n", checkPrime(BigInteger.valueOf(2L), 20));
System.out.printf("checkprime(5) is %b%n", checkPrime(BigInteger.valueOf(5L), 20));
System.out.printf("checkprime(7) is %b%n", checkPrime(BigInteger.valueOf(7L), 20));
System.out.printf("checkprime(9) is %b%n", checkPrime(BigInteger.valueOf(9L), 20));
}
}
如果您明确说明“不起作用”的样子,那么运气会更好。 – duffymo 2010-10-26 19:24:10
“不行”我的意思是它没有给出正确的结果。例如,当我对诸如2,3,5和7等素数进行测试时,它会返回“false”,并返回“true”。 – 2010-10-26 19:30:04
你是否检查过a = new BigInteger(n.bitLength() - 1,rand);打印时确实是一个正常值,并且rand从1正确初始化为n(我没有看到那部分)? – extraneon 2010-10-26 19:30:29