Check a Number is Prime Number or not in C#

Q. 1 What is Prime Number?

Answer :  A prime number (or a prime) is a natural number greater than 1 that has no positivedivisors other than 1 and itself. 

Q. 2 Write a programmer in C# to check number is prime or not ?

Answer : The following code snippet  to check prime number or not.

using System;

namespace PrimeNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter a number");
            int number = Convert.ToInt32(Console.ReadLine());
            int result = Check_Prime(number);
            if (result == 0)
            {
                Console.WriteLine("{0} is not a prime number", number);
            }
            else
            {
                 Console.WriteLine("{0} is  a prime number", number);
            }           
            Console.Read();
        } 

        private static int Check_Prime(int number)
       {
            int i;
            for (i = 2; i <= number - 1; i++)
            {
                if (number % i == 0)
                {
                    return 0;
                }
            }
            if (i == number)
            {
                return 1;
            }
            return 0;
        }
    } 
}

Ebook Download
View all
Learn
View all