Sieve of Eratosthenes



I'm fairly new to programming, and I just started C++

I found this problem, which involved generation all prime numbers upto "n". This is my code, where I've assumed "n" to be 10. I've tried my best. I'd really appreciate it if you guys could tell me what's wrong.

The for loop that's labelled /*A*/is repeating indefinitely, that means the value of i isn't being updated. I used a cout statement to print the value, it's either 0 or 1. Why is this happening? Is there a fault in the logic?

#include<iostream>
#include<cstdlib>

using namespace std;

int main()
{
int NumList[10], flag[10];
int i,j;


for(i = 0; i<10; i++) //Generate a list of numbers from 1 to 10
NumList[i] = i+1;



for(i = 0; i<10; i++) // Create a flag array, initialized to 1
flag[i] = 1;

for(i=1; i<10; i++)
{
if(NumList[i]%2==0) // Mark all even numbers in the list
flag[i] = 0; // since they're not prime
}

/*A*/ for(i = 2; i<10; i++) //Start from 3
{ if(flag[i]==1) // Check which numbers are left over

{
for(j = NumList[i]-1;j<10; ) //Since index = value-1 in this case
{
j+= NumList[i]; //Keep incrementing by value and marking
flag[j] = 0;
}
}
}

}

Note that condition j < 10 will be checked before addition is made.
So if j is for example 5, i is 5 too, it passes check then 5 is added to j and then you are doing flag[10] = 0; which is access out of bounds. Incidentally it is where your compiler stores value of i.
Last edited on
Topic archived. No new replies allowed.