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.
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);
}
}
}
This can be done using Streams as follows:
IntStream.range(2, 1001)
.boxed()
.filter(j -> IntStream.range(2, j).boxed().allMatch(i -> j % i != 0))
.forEach(System.out::println);
First, we:
generate the indices between 2 to 1000 (inclusive) i.e., IntStream.range(2, 1001),
then we convert from IntStream into Integer (i.e., boxed()),
then we filter to only the number that are prime
.filter(j -> IntStream.range(2, j).boxed().allMatch(i -> j % i != 0)),
finally we print out the result.
This kind of pipeline is less prone to the mistakes that you have done in your original code.