Created
October 5, 2011 00:10
-
-
Save einarwh/1263222 to your computer and use it in GitHub Desktop.
Simple iterator for primes.
This file contains hidden or 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 PrimeSequence : IEnumerable<int> | |
| { | |
| public IEnumerator<int> GetEnumerator() | |
| { | |
| return new SimplePrimeEnumerator(); | |
| } | |
| IEnumerator IEnumerable.GetEnumerator() | |
| { | |
| return GetEnumerator(); | |
| } | |
| } | |
| public class SimplePrimeEnumerator : IEnumerator<int> | |
| { | |
| private readonly IEnumerator<int> _candidates = | |
| new NumberSequence(1, 1).GetEnumerator(); | |
| private IPriorityQueue<NumberEnumerator> _pq = | |
| new IntervalHeap<NumberEnumerator>(); | |
| public int Current | |
| { | |
| get { return _candidates.Current; } | |
| } | |
| public bool MoveNext() | |
| { | |
| while (true) | |
| { | |
| _candidates.MoveNext(); | |
| int n = _candidates.Current; | |
| 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; | |
| } | |
| do | |
| { | |
| var temp = _pq.DeleteMin(); | |
| temp.MoveNext(); | |
| _pq.Add(temp); | |
| } while (n == _pq.FindMin().Current); | |
| } | |
| } | |
| object IEnumerator.Current | |
| { | |
| get { return Current; } | |
| } | |
| public void Reset() | |
| { | |
| throw new NotSupportedException(); | |
| } | |
| public void Dispose() {} | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment