Erastothenes

davidb ta-nospam-zz at gmx.at
Thu Jun 14 10:58:20 PDT 2007


Dave Colling wrote:
> Has anyone confirmed that the example showing how to find primes
> by the sieve of Erastothenes actuall works?
> It certainly counts something, but they are not primes!

You're right, definitely not (includes 0, 1, 4, 8, 10, 14, 20, 22, 25, ...)
It still features printf instead of writef and is in my opinion
rather confusing for someone starting to learn by example.
So here's a cleaned up version, placed in the public domain (hint)

David


/* Eratosthenes Sieve prime number calculation. */

module sieve;
import std.stdio;

void main()
{
     writefln("finding prime numbers with: 2 <= prime <= 8191");
     int count;
     bool flags[8192] = true;    // find primes with: 2 <= prime <= 8191
     flags[0] = flags[1] = false;
     for (int i = 2; i < flags.length; i++)
     {
         if (flags[i])           // we have a prime
         {	
             writef(i, " ");
             count += 1;
             int k = i*i;
             // now delete all multiples of the prime
             while (k < flags.length)
             {
                 flags[k] = false;
                 k += i;
             }
         }
     }
     writefln("\nfound %d primes", count);
}


More information about the Digitalmars-d-learn mailing list