- 7th Apr 2023
- 07:37 am
- Admin
C# Homework Question - C# Logical Puzzles, Games, and Algorithms: Sieve Eratosthenes
C# Homework Solution
Here is an example implementation of the Sieve of Eratosthenes algorithm in C#:
using System;
class Program {
static void Main() {
int limit = 100;
bool[] primes = new bool[limit+1];
for (int i = 2; i <= limit; i++) {
primes[i] = true;
}
for (int i = 2; i <= Math.Sqrt(limit); i++) {
if (primes[i]) {
for (int j = i*i; j <= limit; j += i) {
primes[j] = false;
}
}
}
Console.Write("Prime numbers between 2 and {0}: ", limit);
for (int i = 2; i <= limit; i++) {
if (primes[i]) {
Console.Write("{0} ", i);
}
}
}
}
This program initializes an array of boolean values, where primes[i] is initially true for all i between 2 and limit inclusive. It then loops over all integers i between 2 and the square root of limit, checking if primes[i] is true. If it is, it marks all multiples of i as composite by setting primes[j] to false for all j equal to i*i, i*i+i, i*i+2i, and so on, up to limit. Finally, it outputs all values of i between 2 and limit for which primes[i] is true, which represent the prime numbers.