|
|
> But now suppose we refactor it to look like this:
>
> public SortedList<int> FindPrimesBelow(int max)
> {
> SortedList<int> candidates = InitialiseCandidates(max);
> SortedList<int> primes = new SortedList<int>();
>
> while (candidates.Size() > 0)
> {
> int prime = GetNextPrime(candidates);
> primes.Add(prime);
> RemovePrimeAndItsMultiples(prime, candidates, max);
> }
>
> return primes;
> }
>
> private SortedList<int> InitialiseCandidates(int max)
> {
> SortedList<int> candidates = new SortedList<int>();
>
> for (int n=2; n<max; n++)
> {
> candidates.Add(n);
> }
>
> return candidates;
> }
>
> private int GetNextPrime(SortedList<int> candidates)
> {
> return candidates[0];
> }
>
> private int RemovePrimeAndItsMultiples(int prime, SortedList<int>
> candidates, int max)
> {
> for (int k=1; k*prime < max; k++)
> {
> candidates.Remove(k*prime);
> }
> }
So you're writing 3x as much code just to avoid comments? Is the above
really that much more readable to justify the extra work writing it?
public SortedList<int> Primes(int max)
{
SortedList<int> candidates = new SortedList<int>();
SortedList<int> primes = new SortedList<int>();
for (int n=2; n<max; n++) candidates.Add(n); // initialise
while (candidates.Size() > 0)
{
int p = candidates[0]; // get next prime
primes.Add(p);
for (int k=1; k*p < max; k++) candidates.Remove(k*p); // remove
multiples
}
return primes;
}
Post a reply to this message
|
|