-4

I created this loop to find prime numbers, the int num is initialized as 0, but the debugger always skips 1 (which is correct) 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);
        }
    }
}
moondaisy
  • 4,303
  • 6
  • 41
  • 70
kebabjoe
  • 1
  • 1

1 Answers1

0

The problem with your code is that in the case num=2 you don't get into the part where you add the prime number. You chose to use the last iteration of the inner loop as the place where to add a prime number to your list, but with num=2 the inner loop has 0 iterations.

I'd modify your program as follows:

package test;

import java.util.ArrayList;
import java.util.List;

public class Test {

    private static boolean isPrime(int num) {
        for (int j = 2; j < num; j++) {
            if (num % j == 0) {
                return false;
            }
        }
        return true;
    }

    public static void main (String [] args) {    
        List<Integer> myPrimeNumbers = new ArrayList<>();
        for (int num = 2; num <= 100; num++) {
            if (isPrime(num)) {
                System.out.println("PRIME NUMBER FOUND! It's: " + num + ".");
                myPrimeNumbers.add(num);
            }
        }
    }
}

Extracting the prime test into a method makes it easy to place the true and false returns at locations where they are intuitively correct.

And I started the prime number search with 2 instead of 0 as we all know that 0 and 1 are by definition no primes.

Ralf Kleberhoff
  • 6,990
  • 1
  • 13
  • 7