简体   繁体   中英

Fermat's little theorem for prime numbers Java

From What I understood , if P is Prime then a^(p-1)-1 mod p =1 What I want is to print every prime number between two integers What I wrote is :

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;
}

but it keeps running and doesn't stop. What did I do wrong?

BigInteger s are immutable. You need to assign the result of add back to j .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM