Friday 25 May 2012

C# program to print prime numbers


A prime number is not divisible by any other number apart from 1 and itself. So, we use this logic in this program to determine if a number is prime.


using System;


namespace SamplePrograms
{
    class PrimeNumber
    {
        public static void Main()
        {
            // Declare a boolean variable to determine is if a number is prime
            bool isNumberComposite = false;
            int j;


            // Prompt the user to enter their target number
            Console.WriteLine("Enter your Target?");


            // Read the target number and convert to integer
            int target = Int32.Parse(Console.ReadLine());


            // 1 is neither prime nor composite. So start at 2
            for (int i = 2; i <= target; i++)  
            {
                for (j = 2; j < i; j++)
                {
                    // A number is not prime if it is divisible by any other number,
                    // other than 1 and itself.

                    if (i % j == 0)
                    {
                        isNumberComposite = true;
                        // We can break out of the inner for loop as we know the number
                        // is not prime

                        break;
                    }
                }
                // Print the number if it is not composite
                if (!isNumberComposite)
                    Console.Write("{0} ", j);
                else
                    isNumberComposite = false;
            }
            
            // This line is to make the program wait for user input,
            // instead of immediately closing

            Console.ReadLine();
        }
    }
}

0 comments:

Post a Comment


                                                            
 
Design by Abhinav Ranjan Sinha