how many prime numbers are there total? in csharp

Here's a C# code to find and count all prime numbers between 2 and a given number:

main.cs
using System;

class Program {
    static bool IsPrime(int n) {
        if (n < 2) {
            return false;
        }
        for (int i = 2; i <= Math.Sqrt(n); i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }
    
    static void Main(string[] args) {
        Console.WriteLine("Enter a number:");
        int n = int.Parse(Console.ReadLine());
        int count = 0;
        for (int i = 2; i <= n; i++) {
            if (IsPrime(i)) {
                count++;
            }
        }
        Console.WriteLine("There are " + count + " prime numbers between 2 and " + n);
    }
}
654 chars
28 lines

We use a for loop to iterate from 2 to the given number n, and call the IsPrime function to check if each number is prime or not. The IsPrime function checks if the number is less than 2, and then checks if it is divisible by any number between 2 and its square root. If it is divisible by any number, the function returns false (not prime). If the loop completes without finding a divisor, the function returns true (prime).

The program keeps a counter to count the number of prime numbers found, and prints the final count at the end.

gistlibby LogSnag