How To Check If Number Is Prime Or Not In C#

Introduction

In this article, I am going to discuss how to check if the number is prime or not-prime in C# with Examples.prime number is a number that is greater than 1 and divided by 1 or itself.

Example with C# 

Now create a new Console application and add the below code in the program.cs file.

using System;

namespace CheckPrimeInCshap
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Check whether a given number is prime or not:\n");
            Console.Write("-----------------------------------------------");
            Console.Write("\n\n");
            Console.Write("Enter a Number : ");          
            int num = int.Parse(Console.ReadLine());
            Console.WriteLine("\n");

            bool IsPrime = true;

            for (int i = 2; i < num / 2; i++)
            {
                if (num % i == 0)
                {
                    IsPrime = false;
                    break;
                }   
            }
            
            if(IsPrime)
            {
                Console.Write(num + " is Prime Number!");
            }
            else
            {
                Console.Write(num + " is not Prime Number!");
            }
            Console.ReadLine();
        }
    }
}

Here,

  • isPrime is used to check if a given number is prime or not. It returns true if it is prime, else false. We can check up to number/2 if anyone can divide the number or not. It makes the for loop smaller.
  • It is asking the user to enter a number to check. Using ReadLine(), it reads that number and store it in num.
  • Using isPrime, it checks if it is prime or not.
  • Based on the return value of isPrime, it prints one message.

Output 1 :

Output 2 : 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories