/*
   Sieve of Eratosthenes to identify primes between 1 and Nmax.

   Defition: p is prime if it only has 1 and p as divisors. E.g. 7 is a prime
   because it can only be written 7=1*7

   Definition: a is composite if it can be written as a non-trivial product
   e.g. 10=2*5 or 24=2*12=2^3*3 etc.

   1) Why would while (primecandidate[prime] && p<N) be a BUG?

   3) Try saving the primes as polar coordinates  p*cos(p),p*sin(p) and plot the result.

   matlab:
   data=importdata("primes.dat");
   plot(data(:,1),data(:,2),'.');
   axis equal

*/

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    const int N=10;
    vector<bool> primecandidate(N, true);  //  0,..,N-1 filled with true.

    cout << "Before sieve primecandidates are: " << endl;
    for (int i=1;i<N;i++)
        if (primecandidate[i]) cout << i << " ";
    cout << endl;

    // First prime to reject multiples of is p=2
    int p=2;
    do {
        cout << "Marking multiplies of " << p << endl;         

        for (int j=2*p;j<N;j+=p) primecandidate[j]=false;     // 2p,3p, .., j*p, .. as long as j*p<N

        // find next primecandidate, or end of the array (NOTE order)
        p++;                                                  // propose the primecandidate
        while (p<N && !primecandidate[p])                     // test if it is a primecandidate
                                          p++;                // otherwise propose the next

        cout << "Next primecandidate to process " << p << endl;
    }
    while (p<N);                                              // Keep marking multiples until p==N.

    cout << "After sieve primecandidates are: " << endl;
    for (int i=2;i<N;i++)
        if (primecandidate[i]) cout << i << " ";

    cout << endl;

    return 0;
}

