vendredi 4 août 2017

Why is this if-condition always excluding 2?

I created this Loops to find prime numbers, the int num is initialized as 0, but the Debugger always skips 1 (which is correc) and 2 (which is not correct).

How does it come that it always skips 2 % 2 == 0 ?

    for (int num = 0; num <= 100; num++) {
        for (int j = 2; j < num; j++) {
            if (num % j == 0) {
                System.out.println(num + " is not a prime number.");
                break;
            }
            if (num - j == 1) {
                System.out.println("PRIME NUMBER FOUND! It's: " + num + ".");
                myPrimeNumbers.add(num);
            }
        }

    }

Aucun commentaire:

Enregistrer un commentaire