Sieve of Eratosthenes algorithm

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

    I have no idea why you're not getting all the output, as it looks like you should get everything. What output are you missing?

    The sieve is implemented wrongly. Something like

    vector sieve;
    vector primes;
    
    for (int i = 1; i < max + 1; ++i)
       sieve.push_back(i);   // you'll learn more efficient ways to handle this later
    sieve[0]=0;
    for (int i = 2; i < max + 1; ++i) {   // there are lots of brace styles, this is mine
       if (sieve[i-1] != 0) {
          primes.push_back(sieve[i-1]);
          for (int j = 2 * sieve[i-1]; j < max + 1; j += sieve[i-1]) {
              sieve[j-1] = 0;
          }
       }
    }
    

    would implement the sieve. (Code above written off the top of my head; not guaranteed to work or even compile. I don't think it's got anything not covered by the end of chapter 4.)

    Return primes as usual, and print out the entire contents.

提交回复
热议问题