Sieve of Eratosthenes algorithm

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

    From Algorithms and Data Structures:

    void runEratosthenesSieve(int upperBound) {
          int upperBoundSquareRoot = (int)sqrt((double)upperBound);
          bool *isComposite = new bool[upperBound + 1];
          memset(isComposite, 0, sizeof(bool) * (upperBound + 1));
          for (int m = 2; m <= upperBoundSquareRoot; m++) {
                if (!isComposite[m]) {
                      cout << m << " ";
                      for (int k = m * m; k <= upperBound; k += m)
                            isComposite[k] = true;
                }
          }
          for (int m = upperBoundSquareRoot; m <= upperBound; m++)
                if (!isComposite[m])
                      cout << m << " ";
          delete [] isComposite;
    }
    

提交回复
热议问题