Sieve of Eratosthenes algorithm

后端 未结 14 1235
一生所求
一生所求 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:29

    Interestingly, nobody seems to have answered your question about the output problem. I don't see anything in the code that should effect the output depending on the value of max.

    For what it's worth, on my Mac, I get all the output. It's wrong of course, since the algorithm isn't correct, but I do get all the output. You don't mention what platform you're running on, which might be useful if you continue to have output problems.


    Here's a version of your code, minimally modified to follow the actual Sieve algorithm.

    #include 
    #include 
    
    using namespace std;
    
    //finds prime numbers using Sieve of Eratosthenes algorithm
    vector calc_primes(const int max);
    
    int main()
    {
        const int max = 100;
    
        vector primes = calc_primes(max);
    
        for(int i = 0; i < primes.size(); i++)
        {
            if(primes[i] != 0)
                cout< calc_primes(const int max)
    {
        vector primes;
    
        // fill vector with candidates
        for(int i = 2; i < max; i++)
        {
            primes.push_back(i);
        }
    
        // for each value in the vector...
        for(int i = 0; i < primes.size(); i++)
        {
            //get the value
            int v = primes[i];
    
            if (v!=0) {
                //remove all multiples of the value
                int x = i+v;
                while(x < primes.size()) {
                    primes[x]=0;
                    x = x+v;
                }
            }
        }
        return primes;
    }
    

提交回复
热议问题