Help to create a program in JAVA that accepts an integer, displays all prime numbers from zero to the received number. Using only simple if and for operations I compiled, but something does not help import java.util.Scanner;

public class prostue_chisla { public static void main(String[] args) { System.out.println("Введите положительное число: "); Scanner in = new Scanner(System.in); int input = in.nextInt(); boolean b = true; for (int P = 1; P <= input; P++) { for (int i = 1; i < P; i++) { if (P % i == 0){ b = false; } System.out.println(P);} } } } 
  • Why do you need b variable? What exactly is wrong in the above code? - ArchDemon
  • Here is what it gives: Enter a positive number: 5 2 3 3 4 4 4 5 5 5 5 - Igor

4 answers 4

 public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int top = scanner.nextInt(); for (int i=2;i<top;i++){ if(checkSimple(i)) System.out.println(i); } } public static boolean checkSimple(int i){ if (i<=1) return false; else if (i <=3) return true; else if (i%2==0 || i %3 ==0) return false; int n = 5; while (n*n <=i){ if (i % n ==0 || i % (n+2) == 0) return false; n=n+6; } return true; } 

Algorithm for checking that the number is simple took from here: https://en.wikipedia.org/wiki/Primality_test

  • Something still does not work - Igor

The problem is not with the scanner, but with the algorithm. Firstly, it is not optimal, and secondly, it contains an error. But, if you want to search for simple numbers in this way, correct your method this way.

 public static void main(String[] args) { System.out.println("Введите положительное число: "); Scanner in = new Scanner(System.in); int input = in.nextInt(); boolean b = true; for (int P = 2; P <= input; P++) { for (int i = 2; i < P; i++) { if (P % i == 0) { b = false; break; } } if (b) System.out.println(P); else b = true; } } 
  • Here is what gives out: Enter a positive number: 5 2 3 3 4 4 4 5 5 5 5 - Igor
  • maybe you copied something wrong, because it gives me 5 1 2 3 5 - Dmitriy
  • 1 - not easy ... - pavel
  • Thanks, but copied everything correctly - Igor
  • change p = 1 to p = 2 and everything is fine, 1 is not displayed - Dmitry

If you use java 8+ , it is better to use IntStream in your case for integers:

 public static boolean isPrime(final int number) { return IntStream.rangeClosed(2, number / 2).anyMatch(i -> number % i == 0); } 

Using:

 System.out.println(isPrime(1)); // false System.out.println(isPrime(2)); // true 
     //variable 'input' is input numeric for (int i = 2; i <= input; i++) { Integer rez = i; for (int j = 2; j < i; j++) { if (i % j == 0) { rez = null; break; } } if (rez != null) { System.out.println(rez); } }