Omar Chaâbouni
Omar Chaâbouni

Reputation: 15

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?

Upvotes: 1

Views: 1253

Answers (1)

John Kugelman
John Kugelman

Reputation: 361849

BigIntegers 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)) {

Upvotes: 3

Related Questions