Skip to content

Check If A Given Number Is Prime Or Not

In order to execute the code I’ve created a simple console application to print out the result.

Please find complete code below:

Input number: 113

using System;

namespace PracticeConsole
{
   class Program
   {
      static void Main(string[] args)
      {
         Console.WriteLine("Please input any number and then hit enter:");
         int myNumber = Convert.ToInt32(Console.ReadLine());
         bool isPrime = false;
         if (myNumber < 2) isPrime = false;
         if (myNumber % 2 == 0) isPrime = false;
         if (myNumber == 2) isPrime = true;
         for (int i = 3; i * i <= myNumber; i += 2)
         {
            if (myNumber % i == 0)
            {
               isPrime = false;
            }
         }
         isPrime = true;
         Console.WriteLine(isPrime);
         Console.ReadLine();
      }
   }
}

Result: True