Sieve of Eratosthenes algorithm

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

    I think im late to this party but im reading the same book as you, this is the solution in came up with! Feel free to make suggestions (you or any!), for what im seeing here a couple of us extracted the operation to know if a number is multiple of another to a function.

    #include "../../std_lib_facilities.h"
    
    bool numIsMultipleOf(int n, int m) {
      return n%m == 0;
    }
    
    int main() {
      vector rawCollection = {};
      vector numsToCheck = {2,3,5,7};
    
      // Prepare raw collection
      for (int i=2;i<=100;++i) {
        rawCollection.push_back(i);
      }
    
      // Check multiples
      for (int m: numsToCheck) {
        vector _temp = {};
    
        for (int n: rawCollection) {
          if (!numIsMultipleOf(n,m)||n==m) _temp.push_back(n);
        }
        rawCollection = _temp;
      }
    
      for (int p: rawCollection) {
        cout<<"N("<

提交回复
热议问题