Created
July 2, 2021 15:48
-
-
Save sonnemaf/afde94073f19b9863eed785fbfc9e4cc to your computer and use it in GitHub Desktop.
SieveOfEratosthenes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using static System.Console; | |
int start = 1, end = 1000; | |
WriteLine($"The prime numbers between {start} and {end} are :"); | |
BitArray bits = SieveOfEratosthenes(end); | |
for (int i = start; i <= end; i++) | |
{ | |
if (bits[i]) | |
{ | |
Write(i); | |
Write(' '); | |
} | |
} | |
BitArray SieveOfEratosthenes(int limit) | |
{ | |
BitArray bits = new BitArray(limit + 1, true); | |
bits[0] = false; | |
bits[1] = false; | |
for (int i = 0; i * i <= limit; i++) | |
{ | |
if (bits[i]) | |
{ | |
for (int j = i * i; j <= limit; j += i) | |
{ | |
bits[j] = false; | |
} | |
} | |
} | |
return bits; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment