Mid From PDF Coding C# Coding Interview

Generate All Prime Numbers up to N (Sieve of?

Eratosthenes)

List<int> GeneratePrimes(int n)
{
bool[] isPrime = new bool[n + 1];
for (int i = 2; i <= n; i++) isPrime[i] = true;
for (int i = 2; i * i <= n; i++)
{
if (isPrime[i])
{
for (int j = i * i; j <= n; j += i)
isPrime[j] = false;
}
}
List<int> primes = new List<int>();
for (int i = 2; i <= n; i++)
{
if (isPrime[i]) primes.Add(i);
}
return primes;
}

Explanation:

Mark multiples of each prime as non-prime starting from its square.

Follow on:

More from C# Programming Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details