Created
October 5, 2011 00:35
-
-
Save einarwh/1263286 to your computer and use it in GitHub Desktop.
An enumerator for the odd primes (i.e. all but 2)
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
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