Skip to content

Instantly share code, notes, and snippets.

@PrashantUnity
Forked from SuprDewd/SieveOfEratosthenes.cs
Created January 8, 2022 18:21
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 PrashantUnity/d8c4a0598803214bab26bd4aafdab23b to your computer and use it in GitHub Desktop.
Save PrashantUnity/d8c4a0598803214bab26bd4aafdab23b to your computer and use it in GitHub Desktop.
Sieve Of Eratosthenes
using System;
using System.Collections.Generic;
using System.Linq;
namespace Primes
{
public static IEnumerable<int> SieveOfEratosthenes(int upperLimit)
{
int sieveBound = (upperLimit - 1) / 2,
upperSqrt = ((int)Math.Sqrt(upperLimit) - 1) / 2;
bool[] PrimeBits = new bool[sieveBound + 1];
yield return 2;
for (int i = 1; i <= upperSqrt; i++)
{
if (!PrimeBits[i])
{
yield return 2 * i + 1;
for (int j = i * 2 * (i + 1); j <= sieveBound; j += 2 * i + 1)
{
PrimeBits[j] = true;
}
}
}
for (int i = upperSqrt + 1; i <= sieveBound; i++)
{
if (!PrimeBits[i])
{
yield return 2 * i + 1;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment