Advertisement
Guest User

Untitled

a guest
Nov 17th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.60 KB | None | 0 0
  1. //01151424 David Karasz
  2.  
  3. public class Bsp06 {
  4.  
  5.  
  6.     public static void main(String[] args) {
  7.         System.out.println("Alle Primzahlen in [m, n]");
  8.         System.out.print("m: ");
  9.         int m = SavitchIn.readInt();
  10.         System.out.println();
  11.         System.out.print("n: ");
  12.         int n = SavitchIn.readInt();
  13.         System.out.println();
  14.         System.out.println(String.format("Alle Primzahlen in [%d, %d]:", m, n));
  15.  
  16.  
  17.         boolean[] primes = findPrimes(m, n);
  18.         int primesCount = printPrimes(primes, m);
  19.         System.out.println("Insgesamt " + primesCount + " Primzahlen.");
  20.     }
  21.  
  22.     public static boolean isPrime(int n) {
  23.            //ueberprueft ob n eine Primzahl ist
  24.               int k = 2;  
  25.                  
  26.               while((k <= n) && (n%k != 0) && (n > 1))
  27.                  k++;
  28.              
  29.               return k == n;
  30.            }
  31.    
  32.  
  33.     public static boolean[] findPrimes(int m, int n) {
  34.         if (n < m) return null;
  35.         int size = n - m + 1;
  36.         boolean[] primes = new boolean[size];
  37.         for (int i = m; i <= n; i++) {
  38.             primes[i - m] = isPrime(i);
  39.         }
  40.         return primes;
  41.     }
  42.  
  43.     public static int printPrimes(boolean[] foundPrimes, int m) {
  44.         int primes = 0;
  45.         for (int i = 0; i < foundPrimes.length; i++) {
  46.             if (foundPrimes[i]) {
  47.                 System.out.print(m + i + " ");
  48.                 primes++;
  49.             }
  50.         }
  51.         System.out.println();
  52.         return primes;
  53.     }
  54.  
  55.     public static boolean[] sieveOfEratosthenes(int m, int n) {
  56.         return findPrimes(m, n);
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement