Hello everyone, Im currently working on an assignment for school, and I have to implement the Sieve of Eratosthenes to find all prime numbers in my program between the ranges of the numbers 2 and 300.
Im having a lot of trouble with the algorithm itself. I've been at it for nearly two days straight, and I'm starting to feel incapable of doing it. I've looked at a lot of different code to get some ideas. However I can't seem to implement it correctly.
I need to use the .erase( .begin( ) + n ) function to delete the numbers from a vector in the program.
It seems to work "okay for the first 5 numbers, but after that it fails miserably.
As you can see i created two for loops, and one is inside the other. For the second for loop i set the variable i equal to the value of the element being used.Code:void Eratos (int length, vector <int> &p_list) { // generate list of numbers up to specified length for (int number = 2; number <= length; ++number) { p_list.push_back(number) ; } for(int index = 0; index < p_list.size(); index++) { if(p_list[index]) { for(int i = p_list[index]; i < p_list.size(); i++) { p_list.erase( p_list.begin() + i ); } } } for (int index = 0; index < p_list.size(); index++) { cout << p_list[index] << endl; } }
The loop is supposed to accomplish something like this:
let i in the inner loop be equal to the value of the first element in the vector ( 2 ).
Start from the beginning of the vector and count twice over.
it always resets back to the beginning of the vector after completing a loop, and counts with the new increment.
So: Let assume a range from 2 - 10
Original vector :2 3 (4) 5 6 7 8 9 10
4 is deleted.
2 3 5 6 7 8 9 10
then i increments to 3
2 3 5 (6) 7 8 9 10
10 is deleted;
then i increments to 4;
2 3 5 7 (8) 9 10
8 is deleted and so on.
as i increases, the p_list.size() decreases so that way it eventually becomes equal to p_list.size and the loop stops, then repeats with the next element value.
Any suggestion would be great, thanks and sorry for the long read.