June 23, 2017

Write a C# Program To Check If a Number Is Prime Or Not


Write a C# Program To Check If a Number Is Prime Or Not?

This C# Program Checks Whether the Given Number is a Prime number if so then Display its Largest Facor. Here first the number that is obtained is checked whether the number is prime or not and then the largest factor of it is displayed.

A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.

/*
 * C# Program to Check Whether the Given Number is a Prime number if so then
 * Display its Largest Factor
 */
using System;
namespace example
{
    class prime
    {
        public static void Main()
        {
            Console.Write("Enter a Number : ");
            int num;
            num = Convert.ToInt32(Console.ReadLine());
            int k;
            k = 0;
            for (int i = 1; i <= num/2; i++)
            {
                if (num % i == 0)
                {
                    k++;
                }
            }
            if (k == 2)
            {
                Console.WriteLine("Entered Number is a Prime Number and the Largest Factor is {0}",num);
            }
            else
            {
                Console.WriteLine("Not a Prime Number");
            }
            Console.ReadLine();
        }
    }
}

Output:

Enter a Number : 11
Entered Number is a Prime Number and the Largest Factor is 11



Subscribe to get more Posts :