Count number of prime numbers in a given range

A prime number is a number that is greater than 1 and can not be the product of two smaller numbers. In short, a Prime number is a number can’t be divided by other numbers than itself or 1. For example 2, 3, 5, 7, 11, 13, 17, 19, 23..

C# program that returns the count of prime numbers in a given range

using System;

namespace PrimeNumberCount
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a number until you want to check prime number count : ");
            int n = int.Parse(Console.ReadLine());
            bool[] primes = new bool[n];
            int count = 0;
            for (int i = 0; i < n; i++)
            {
                if (i == 0 || i == 1)
                {
                    primes[i] = false;
                }
                else
                {
                    primes[i] = true;
                }

            }

            for (int i = 2; i < n; i++)
            {
                for (int j = 2; i * j < n; j++)
                {
                    primes[i * j] = false;
                }
            }

            for (int i = 0; i < n; i++)
            {
                if (primes[i] == true)
                    count += 1;
            }

            Console.WriteLine($"Count is {count}");
        }
    }
}

Output:

Enter a number until you want to check prime number count : 50
Count is 15

 

Leave a Comment?