Friday, 4 April 2014

C#.NET program to check whether a given number is prime number or not.

Prime number:
A number which is greater than 1 and divisible by 1 or itself is called prime number.
2 is an even prime number because it is evenly divisible by itself and divisible by 1.
All even numbers are not prime numbers. If the last digit of the number contains 0 2 4 6 8 then the number divisible by 2 thus the number is not a prime number.

Ex: First few prime numbers are 2, 3, 5, 7, 11, 13 ..........

Here I am posting a code snippet to find whether a given number is prime number or not.


C# Program For Prime Number

using System;

namespace ConsoleApplication1
{

    class Program
    {
        static void Main()
        {
            Console.Write("Please enter number to check prime or not: ");
            long inputValue = Convert.ToInt32(Console.ReadLine());

            if (IsPrimeNumber(inputValue))
            {
                Console.WriteLine(inputValue + " is prime number");
            }
            else
            {
                Console.WriteLine(inputValue + " is not prime number");
            }

            Console.ReadLine();
        }

        private static bool IsPrimeNumber(long inputValue)
        {
            if (inputValue == 0 ||inputValue == 1)
            {
                return false;
            }

            if (inputValue == 2)
            {
                return true;
            }

            var roundedVal = (long)Math.Round(Math.Sqrt(inputValue));

            for (long i = 2; i <= roundedVal; i++)
            {
                if (inputValue % i == 0)
                {
                    return false;
                }
            }
            return true;
        }

    }
}

Output:

















No comments: