Inspired by YouTube video, Advanced Topics in Programming Languages: Concurrency/message passing Newsqueak.
public IEnumerable<int> Primes(int max)
{
int count = 0;
int candidatePrime = 2;
var primes = new List<int>(max);
while (count < max)
{
while (primes.Any(prime => candidatePrime % prime == 0)) candidatePrime++;
yield return candidatePrime;
primes.Add(candidatePrime);
count++;
}
}Thoughts about the implementation:
- We don't really need to pass in
maxor maintaincount:- The caller could/should be responsible for breaking out of the iteration
- We don't need to set the initial capacity of the
List- we should trust the underlying
Listimplementation to be efficient; or - we could build a custom implementation to efficiently manange the memory
- we should trust the underlying
- Using Linq's
Any()is really nice as I don't need to put any thought into when to incrementcandidatePrime- A custom implementation would likely be faster
Another implementation of prime generation can be seen here: https://gist.github.com/mcmullm2-dcu/648f08f3c4e96e368cbf7f4c47e0cb74