Sieve of Eratosthenes algorithm

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

    Here's my implementation not sure if 100% correct though : http://pastebin.com/M2R2J72d

    #include
    #include  
    
    using namespace std;
    void listPrimes(int x);
    
    int main() {
    
        listPrimes(5000);
    }
    
    void listPrimes(int x) {
        bool *not_prime = new bool[x];
        unsigned j = 0, i = 0;
    
        for (i = 0; i <= x; i++) {
            if (i < 2) {
                not_prime[i] = true;
            } else if (i % 2 == 0 && i != 2) {
                not_prime[i] = true;
            }
        }
    
        while (j <= x) {
            for (i = j; i <= x; i++) {
                if (!not_prime[i]) {
                    j = i;
                    break;
                }
            }
            for (i = (j * 2); i <= x; i += j) {
                not_prime[i] = true;
            }
            j++;
        }
    
        for ( i = 0; i <= x; i++) {
            if (!not_prime[i])
                cout << i << ' ';
        }
    
        return;
    }
    

提交回复
热议问题