Sabari M Sabari M
Updated date Feb 23, 2021
This code snippet explains how to check a number is a prime number or not in C#. A prime number is a number that is greater than 1 and divided by 1 or itself.

This code snippet explains how to check a number is a prime number or not in C#. A prime number is a number that is greater than 1 and divided by 1 or itself. For example, prime numbers are  2, 3, 5, 7, 11, 13, 17, 19, 23....

using System;

namespace SampleProgram
{
    class PrimeExample
    {
        static void Main()
        {
            // Get input
            Console.WriteLine("Enter a number:");
            int number = Convert.ToInt32(Console.ReadLine());   
            
            // Check whether the given number is prime or not
            if (IsPrimeNumber(number))            
                Console.WriteLine("{0} is a prime number", number);                            
            else            
                Console.WriteLine("{0} is not a prime number", number);            
            Console.ReadKey();
        }

        // This method returns the bool value. i.e., True for prime and False for non-prime numbers
        private static bool IsPrimeNumber(int number)
        {
            int x = 0;
            for (int i = 1; i <= number; i++)
            {
                if (number % i == 0)
                {
                    x++;
                }
            }
            if (x == 2)
            {
                return true;
            }
            return false;
        }
    }
}

Output 1:

Enter a number:
2
2 is a prime number

Output 2:

Enter a number:
8
8 is not a prime number

 

ABOUT THE AUTHOR

Sabari M
Sabari M
Software Professional, India

IT professional with 14+ years of experience in Microsoft Technologies with a strong base in Microsoft .NET (C#.Net, ASP.Net MVC, ASP.NET WEB API, Webservices,...Read More

https://www.techieclues.com/profile/alagu-mano-sabari-m

Comments (0)

There are no comments. Be the first to comment!!!