Prime Numbers in C# Tutorial

Prime Number in C#:

Prime Numbers are the number which is not divisible by any number. Prime Numbers are Only Divisible by its own. 0 and 1 are not Prime Number as Prime Number starts from 2. Examples of Prime Numbers are 2, 3, 5, 7 ….
Prime number in C# can be calculated by various ways. We will calculate it by Using for loop.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Prime_Number
    class Program
        static void Main(string[] args)
            Console.WriteLine("Enter number"); //Asking for the limit to which prime numbers will be calculated
            int upper_limit = Convert.ToInt32(Console.ReadLine());
            for (int i = 2; i < upper_limit; i++)  // Prime Number Starts from 2 so we are starting loop from 2 to upper limit
                if (IsPrimeNumber(i) == true// Calling Prime Number Function whose data type is bool
                    Console.Write("{0}\t", i);

        static bool IsPrimeNumber(int number)  //   Parameter below upper limit
            bool initial_Prime = true;    //   taking it as true initially
            int factor = number / 2;   // dividing the number which we want to check by 2
            int i;
            for (i = 2; i <= factor; i++)  // we will calculate remainder from 2 to half of the number
                if ((number % i) == 0)   // if remainder is 0, then it can be divided by another number , hence not a prime number
                    initial_Prime = false;
            return initial_Prime; 



Thank You for reading this. Like this if you understood, it helps a lot to keep us motivated


Post a Comment