Skip to content

Instantly share code, notes, and snippets.

@einarwh
Created October 5, 2011 00:35
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 einarwh/1263286 to your computer and use it in GitHub Desktop.
Save einarwh/1263286 to your computer and use it in GitHub Desktop.
An enumerator for the odd primes (i.e. all but 2)
public class OddPrimeEnumerator : IEnumerator<int>
{
private readonly IEnumerator<int> _candidates =
new NumberEnumerator(3, 2);
private readonly IPriorityQueue<NumberEnumerator> _pq =
new IntervalHeap<NumberEnumerator>();
public int Current
{
get { return _candidates.Current; }
}
public bool MoveNext()
{
while (true)
{
_candidates.MoveNext();
int n = _candidates.Current;
bool crossedOut = false;
while (!crossedOut)
{
if (_pq.IsEmpty || n < _pq.FindMin().Current)
{
// There are no pending prime-multiples.
// This means n is a prime!
_pq.Add(new NumberEnumerator(n * n, n));
return true;
}
crossedOut = n == _pq.FindMin().Current;
do
{
var temp = _pq.DeleteMin();
temp.MoveNext();
_pq.Add(temp);
} while ((n > _pq.FindMin().Current) ||
(crossedOut && n == _pq.FindMin().Current));
}
}
}
object IEnumerator.Current
{
get { return Current; }
}
public void Dispose() { }
public void Reset()
{
throw new NotSupportedException();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment