Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.32 KB | None | 0 0
  1. public class Sieb {
  2.    
  3.     static int n = 1000000;
  4.     static boolean sieb[] = new boolean[n];
  5.     static int counter = 0;
  6.     static String primzahlen = "";
  7.  
  8.     public static void main(String[] args) {
  9.         // Schritt 0: Initialisiere alles mit false
  10.         for(int i=0; i<n; i++) {
  11.             sieb[i] = false;
  12.         }
  13.        
  14.        
  15.         // Schrit 1: Markiere die Zahl 1
  16.         // Anmerkung: Array Indizes starten bei 0
  17.         sieb[0] = true;
  18.         counter++;
  19.        
  20.         // Schritt 2: Counter zeigt aktuell auf die erste nicht eingerahmte Primzahl
  21.         // Anmerkung: Bei uns passiert hier nichts
  22.        
  23.         while(counter*counter <= n) {
  24.             //Schritt 3: Streiche alle Vielfache durch
  25.             // i+=counter+1  ===   i = i + (counter + 1)
  26.             for(int i=2*(counter+1)-1; i<n; i+=counter+1) {
  27.                 //System.out.println(i+1);
  28.                 sieb[i] = true;
  29.             }
  30.            
  31.             // Gehe zur nächsten Zahl
  32.             counter++;
  33.            
  34.             // Überspringe alle Zahlen, die true sind, weil diese bereits markiert worden sind
  35.             // while(sieb[counter] == true) {
  36.             while(sieb[counter]) {
  37.                 counter++;
  38.             }
  39.         }
  40.        
  41.         // Gib alle unmarkierten Zahlen aus
  42.         for(int i=0; i<n; i++) {
  43.             //if(sieb[i] == false) {
  44.             if(!sieb[i]) {
  45.                 //System.out.println(i+1);
  46.                 primzahlen += Integer.toString(i+1) + ", ";
  47.             }
  48.         }
  49.         primzahlen = primzahlen.substring(0, primzahlen.length() - 2);
  50.         System.out.println(primzahlen);
  51.        
  52.     }
  53.  
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement