I am trying to write a code that checks if a number between 2 and 1000 is a prime Number

Tags:



import java.util.Scanner;

public class Main {

  public static void main(String[] args) {
  
    for(int j = 2; j<=1000; j++) {
        boolean yes = true;
        for(int i = 2; i<j && yes== true; i++){
            if(j%i==0) {
                yes=false;
            }
        System.out.println(j + ":" + yes); 
      } 
    }  
  }
}      

I am trying to understand where is the problem without any answer so far.

Answer

You need to move System.out.println(j + ":" + yes); out of the inner loop. The reason why you need to move it out is that if the number is prime or not is decided only after the inner loop is finished.

public class Main {
    public static void main(String[] args) {
        for (int j = 2; j <= 1000; j++) {
            boolean yes = true;
            for (int i = 2; i < j && yes == true; i++) {
                if (j % i == 0) {
                    yes = false;
                }
            }
            if (yes) {
                System.out.println(j + ":" + yes);
            }
        }
    }
}

Side note: You are not required to check up to i < j. It can be i <= Math.sqrt(j). Check https://en.wikipedia.org/wiki/Primality_test to learn more about it.

Also, if you want to print the false as well, do not use the if (yes) {} block.

public class Main {
    public static void main(String[] args) {
        for (int j = 2; j <= 1000; j++) {
            boolean yes = true;
            for (int i = 2, n = (int) Math.sqrt(j); i <= n && yes == true; i++) {
                if (j % i == 0) {
                    yes = false;
                }
            }

            System.out.println(j + ":" + yes);

        }
    }
}


Source: stackoverflow