Skip to content

Instantly share code, notes, and snippets.

@einarwh
Created October 5, 2011 01:12
Show Gist options
  • Select an option

  • Save einarwh/1263345 to your computer and use it in GitHub Desktop.

Select an option

Save einarwh/1263345 to your computer and use it in GitHub Desktop.
A prime number enumerator that uses wheel factorization.
public class WheelPrimeEnumerator : IEnumerator<int>
{
private readonly IEnumerator<int> _candidates =
new WheelSequence(11,
new BrokenRecord<int>(
new[] { 4, 2, 4, 2, 4, 6, 2, 6 }
)
).GetEnumerator();
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