Advertisement
Guest User

Untitled

a guest
Sep 19th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.14 KB | None | 0 0
  1. import java.io.*;
  2. public class primzahl {
  3.     public static String tmp;
  4.     public static int i;
  5.     public static void main(String[] args) throws IOException {
  6.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  7.     try {
  8.         System.out.println("Bitte geben sie die Maximale länge der zu berechnenden Zahlen ein.");
  9.         tmp = br.readLine();
  10.         } catch (IOException io) {
  11.             System.out.println("Error beim einlesen der Tastatureingaben");
  12.             }
  13.             int max = 0;
  14.             max = Integer.parseInt(tmp);
  15.             boolean[] isPrim = new boolean[max + 1];
  16.         // Initialierung des Arrays
  17.         for (int i = 0; i <= max; i++)
  18.         isPrim[i] = true;
  19.         // 0 und 1 sind keine Primzahlen
  20.     isPrim[0] = isPrim[1] = false;
  21.     // alle Vielfachen von Ganzzahlen ausschließen,
  22.     // die kleiner als die Quadratwurzel von max sind.
  23.     int n = (int) Math.ceil(Math.sqrt(max));
  24.     for (int i = 0; i <= n; i++)
  25.     if (isPrim[i])
  26.     for (int j = 2 * i; j <= max; j+=i)
  27.     isPrim[j] =false;
  28.     // Primzahlen ausgeben
  29.     System.out.print("Primzahlen anzeigen von 0 bis " + max + ": ");
  30.     for (i = 0; i <= max; i++)
  31.     if (isPrim[i])
  32.     System.out.print(" " + i + " ");
  33.     System.out.println();
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement