Sieve of Eratosthenes algorithm

后端 未结 14 1205
一生所求
一生所求 2020-12-15 12:55

I am currently reading \"Programming: Principles and Practice Using C++\", in Chapter 4 there is an exercise in which:

I need to mak

14条回答
  •  天命终不由人
    2020-12-15 13:23

    Think of the sieve as a set.
    Go through the set in order. For each value in thesive remove all numbers that are divisable by it.

    #include 
    #include 
    #include 
    #include 
    
    
    typedef std::set   Sieve;
    
    int main()
    {
        static int const max = 100;
    
        Sieve   sieve;
    
        for(int loop=2;loop < max;++loop)
        {
            sieve.insert(loop);
        }
    
    
        // A set is ordered.
        // So going from beginning to end will give all the values in order.
        for(Sieve::iterator loop = sieve.begin();loop != sieve.end();++loop)
        {
            // prime is the next item in the set
            // It has not been deleted so it must be prime.
            int             prime   = *loop;
    
            // deleter will iterate over all the items from
            // here to the end of the sieve and remove any
            // that are divisable be this prime.
            Sieve::iterator deleter = loop;
            ++deleter;
    
            while(deleter != sieve.end())
            {
                if (((*deleter) % prime) == 0)
                {
                    // If it is exactly divasable then it is not a prime
                    // So delete it from the sieve. Note the use of post
                    // increment here. This increments deleter but returns
                    // the old value to be used in the erase method.
                    sieve.erase(deleter++);
                }
                else
                {
                    // Otherwise just increment the deleter.
                    ++deleter;
                }
            }
        }
    
        // This copies all the values left in the sieve to the output.
        // i.e. It prints all the primes.
        std::copy(sieve.begin(),sieve.end(),std::ostream_iterator(std::cout,"\n"));
    
    }
    

提交回复
热议问题