I am beginning to learn c++, and was working through the Project Euler challenges, and #7 asks you to find all prime numbers within a given range. After online research i decided to try using Sieve of Erastothenes, however with the code i have set up, i currently get weird values such as )2, 0) when i ask for 2 primes, and (2, 4, 5, 5) when i input 5.
#include <iostream>
#include <vector>
#include <math.h>
#include <bits/stdc++.h>
using namespace std;
int main(){
int end_point;
cout << "how many prime numbers would you like to find?\n";
cin >> end_point;
//creates a vector to store all values, that will eventually be whittled down to primes
vector<int> primes = {2};
//adds all numbers between 2 and chosen end point to the vector
for (int i = 3; i <= end_point; i++){
primes.push_back(i);
}
for (int i = 0; i < end_point; i++){
//starts at the first value (always 2), and feeds it into the next for loop
//once the next loop is done, it moves on to the next value in the loop and feeds that in
primes[i];
//looks at values in the vector, starting with the next value in the vector
for (unsigned int j = i+1; j < primes.size(); j++){
//checks if the value at [j] is divisible by the value at [i]
//if it is, this deletes it from the vecotr
//if not, it moves on to the next value in the vector
if(primes[j] % primes[i] == 0){
primes.erase (primes.begin() + (j-1));
}
else{}
}
//prints out all of the primes in the specified range
cout << "Primes are: ";
for (unsigned int k = 0; k <= primes.size(); k++){
cout << primes[k] << ", ";
}
}
}