I am currently reading "Programming: Principles and Practice Using C ++", in chapter 4 there is an exercise in which:
I need to make a program to calculate primes from 1 to 100 using the Sieve of Eratosthenes algorithm.
This is the program I came up with:
#include <vector> #include <iostream> using namespace std; //finds prime numbers using Sieve of Eratosthenes algorithm vector<int> calc_primes(const int max); int main() { const int max = 100; vector<int> primes = calc_primes(max); for(int i = 0; i < primes.size(); i++) { if(primes[i] != 0) cout<<primes[i]<<endl; } return 0; } vector<int> calc_primes(const int max) { vector<int> primes; for(int i = 2; i < max; i++) { primes.push_back(i); } for(int i = 0; i < primes.size(); i++) { if(!(primes[i] % 2) && primes[i] != 2) primes[i] = 0; else if(!(primes[i] % 3) && primes[i] != 3) primes[i]= 0; else if(!(primes[i] % 5) && primes[i] != 5) primes[i]= 0; else if(!(primes[i] % 7) && primes[i] != 7) primes[i]= 0; } return primes; }
Not the best or fastest, but I'm still in the early stages of the book and know little about C ++.
Now the problem is, until max is more than 500 , all values โโwill be printed on the console, if max > 500 not all will be printed.
Am I doing something wrong?
PS: Any constructive criticism will also be appreciated.
RaouL source share