Advertisement
MBrendecke

PrimeNumbers

Mar 19th, 2016
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.29 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace PrimeNumbers
  7. {
  8.     class Program
  9.     {
  10.         static bool[] arr;
  11.  
  12.         static void Main(string[] args)
  13.         {
  14.             int input = 0;
  15.             do
  16.             {
  17.                 Console.Clear();
  18.                 Console.Write("Bitte Zahl eingeben: ");
  19.                 int.TryParse(Console.ReadLine(), out input);
  20.                 if (input < 0)
  21.                 {
  22.                     input = 0;
  23.                 }
  24.                 InitArray(input);
  25.                 Console.WriteLine(!arr[input] ? "Zahl ist Prim." : "Zahl ist nicht Prim.");
  26.             } while (Console.ReadKey().Key != ConsoleKey.Escape);
  27.         }
  28.  
  29.         static void InitArray(int n)
  30.         {
  31.             if (n < 2)
  32.             {
  33.                 n = 2;
  34.             }
  35.  
  36.             arr = new bool[n + 1];
  37.  
  38.             arr[0] = true;
  39.             arr[1] = true;
  40.  
  41.             int length = arr.Length;
  42.             for (int i = 2; i < length; i++)
  43.             {
  44.                 if (!arr[i])
  45.                 {
  46.                     for (int j = 2 * i; j < length; j += i)
  47.                     {
  48.                         arr[j] = true;
  49.                     }
  50.                 }
  51.             }
  52.         }
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement