Sieve of Eratosthenes algorithm

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

    below is my version which basically uses a bit vector of bool and then goes through the odd numbers and a fast add to find multiples to set to false. In the end a vector is constructed and returned to the client of the prime values.

    std::vector  getSieveOfEratosthenes ( int max )
    {
      std::vector primes(max, true);
      int sz = primes.size();
    
      for ( int i = 3; i < sz ; i+=2 )
        if ( primes[i] ) 
          for ( int j = i * i; j < sz; j+=i)
            primes[j] = false;
    
      std::vector ret;
      ret.reserve(primes.size());
      ret.push_back(2);
    
      for ( int i = 3; i < sz; i+=2 )
        if ( primes[i] )
          ret.push_back(i);
    
      return ret;
    }
    

提交回复
热议问题