费马的质数Java定理

时间:2015-01-19 21:13:14

标签: java

根据我的理解,如果P是Prime,那么a^(p-1)-1 mod p =1 我想要的是在两个整数之间打印每个素数 我写的是:

public static void main(String[] args) {

    Scanner r = new Scanner(System.in);
    int x = Integer.parseInt(r.nextLine());
    for (int i = 0; i < x; i++) {
        String s = r.nextLine();
        BigInteger n = new BigInteger(s.split(" ")[0]);
        BigInteger m = new BigInteger(s.split(" ")[1]);

        for (BigInteger j = n; j.compareTo(m) <= 0; j.add(BigInteger.ONE)) {
            if (isPrime(j)) {
                System.out.println(j);

            }
        }
    }

}

private static boolean isPrime(BigInteger num) {
    BigInteger a = num.subtract(num.divide(new BigInteger("2")));
    a = a.modPow(num.subtract(BigInteger.ONE), num);
    if (a == BigInteger.ONE) {
        return true;
    }
    return false;
}

但它一直在运行并且不会停止。我做错了什么?

1 个答案:

答案 0 :(得分:3)

BigInteger是不可变的。您需要将add的结果分配回j

for (BigInteger j = n; j.compareTo(m) <= 0; j = j.add(BigInteger.ONE)) {