MBrendecke icon

PrimeNumbers

MBrendecke | PRO | 03/19/16 07:59:32 PM UTC | 0 ⭐ | 445 👁️ | Never ⏰ | []
C# |

1.29 KB

|

None

|

0 👍

/

0 👎

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace PrimeNumbers
{
    class Program
    {
        static bool[] arr;
 
        static void Main(string[] args)
        {
            int input = 0;
            do
            {
                Console.Clear();
                Console.Write("Bitte Zahl eingeben: ");
                int.TryParse(Console.ReadLine(), out input);
                if (input < 0)
                {
                    input = 0;
                }
                InitArray(input);
                Console.WriteLine(!arr[input] ? "Zahl ist Prim." : "Zahl ist nicht Prim.");
            } while (Console.ReadKey().Key != ConsoleKey.Escape);
        }
 
        static void InitArray(int n)
        {
            if (n < 2)
            {
                n = 2;
            }
 
            arr = new bool[n + 1];
 
            arr[0] = true;
            arr[1] = true;
 
            int length = arr.Length;
            for (int i = 2; i < length; i++)
            {
                if (!arr[i])
                {
                    for (int j = 2 * i; j < length; j += i)
                    {
                        arr[j] = true;
                    }
                }
            }
        }
    }
}

Comments