Skip to content

Instantly share code, notes, and snippets.

@sonnemaf
Created July 2, 2021 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sonnemaf/afde94073f19b9863eed785fbfc9e4cc to your computer and use it in GitHub Desktop.
Save sonnemaf/afde94073f19b9863eed785fbfc9e4cc to your computer and use it in GitHub Desktop.
SieveOfEratosthenes
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