#include <iostream>
#include <vector>
int main()
{
vector<int> primes;
int n = 100; // amount of numbers - 1
vector<bool> sieve;
for (int i = 0; i <= n; i++) { // creating vector with all true values
sieve.push_back(true);
}
// let's set 0 and 1 to false because well we know they're not prime already.
sieve[0] = false;
sieve[1] = false;
// we'll make it so all elements that are set to true are prime numbers.
int p = 2; // setting p to first prime number.
while (p != 11) {
int i = 2 * p;
for (int j = 1; j <= (n / p) - 1; j++) { // sets all p's multiples to false.
sieve[i] = false;
i = i + p;
}
for (int i = 2; i <= 100; i++) { // checking for first number greater than p
// that is prime and setting p equal to it
if (sieve[i] == true && i > p) {
p = i;
break;
}
}
}
for (int i = 0; i < sieve.size(); i++) {
if (sieve[i] == true) { // if the number is prime:
primes.push_back(i); // put it into the primes vector.
}
}
for (int x: primes) {
cout << x << endl;
}
cin >> n;
}
First question: Is this like a terrible way to implement the algorithm? I had trouble doing this and finally came up with this solution but I don't know if it's terrible and a very bad way.
Second question: do you know how I can possibly change the while
condition to make it more flexible? In my case I made it p!=11
because in the range 1-100 there's no point in checking for primes after 7; the program will find the next prime after 7 to be 11 but I'll stop it from continuing. If I want to make it keep going I'll have to change the while
loop condition or find some solution to make it stop running after it's found all primes in the range; how can I do this?