Friday, 4 April 2014

C#.NET Program to generate Prime Numbers

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 how to generate Prime Numbers.

C# Prime Numbers Generator

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class PrimeNumbers
    {
        static void Main()
        {
            Console.Write("Please enter a number to generate prime numbers: ");

            var ipVal = Convert.ToInt64(Console.ReadLine());

            var primeNumbers = GetPrimeNumbersUpTo(ipVal);

            PrintPrimeNumbers(primeNumbers, ipVal);

            Console.ReadLine();
        }

        private static void PrintPrimeNumbers(List<long> primeNumbers, long range)
        {
            Console.WriteLine();
            Console.WriteLine("Prime numbers between 2 to " + range);
            foreach (long item in primeNumbers)
            {
                Console.WriteLine(item);
            }
        }

        private static List<long> GetPrimeNumbersUpTo(long ipVal)
        {
            var primeList = new List<long>();
            for (long value = 2; value <= ipVal; value++)
            {
                if (IsPrimeNumber(value))
                {
                    primeList.Add(value);
                }
            }
            return primeList;
        }

        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: