find all prime numbers in csharp

To find all prime numbers in C#, you can use the 'Sieve of Eratosthenes' algorithm. Here's the code:

main.cs
int n = 100;  // we want to find prime numbers up to 100
bool[] primes = new bool[n+1];  // array to store if number is prime, initialized to false

// initialize all numbers as potential prime numbers
for (int i = 2; i <= n; i++)  
{
    primes[i] = true;
}

// iterate from 2 to sqrt(n) and mark all multiples of each prime number as composite numbers
for (int i = 2; i <= Math.Sqrt(n); i++)  
{
    if (primes[i])
    {
        for (int j = i * i; j <= n; j += i)
        {
            primes[j] = false;
        }
    }
}

// print out all prime numbers
for (int i = 2; i <= n; i++)  
{
    if (primes[i])
    {
        Console.Write(i + " ");
    }
}
656 chars
30 lines

In this algorithm, we initialize an array of booleans to keep track of whether each number is prime or not. We start by assuming that all numbers are potential prime numbers, then we iterate through the array and mark all multiples of each prime number as composite numbers. Finally, we print out all the prime numbers.

This algorithm has a time complexity of O(n*log(log(n))), which is much faster than checking each number for primality individually.

gistlibby LogSnag