Shows segmentation

here is my code


i tried to store all the primes in a vector but I am facing some problems I would be grateful if you can solve this thank you

Hello @gurkirat2600,

There are two errors in your code:

  • vector a is empty while you are iterating over it so, specify size while declaring it, like this.

vector a(max_size,0);

  • in Line 9, you need to iterate from 3 to sqrt(max_size)

for(int i=3;i<max_size;i+=2) change it to
for(int i=3;i*i<max_size;i+=2)

i made the suggested changes but the code fails at test case 3 and also explain why to initilize the vector

@gurkirat2600,

500000th prime = 7,368,787 but your max_size is 500005;
So, increase the limit of the max_size variable.

@gurkirat2600,

You need to iterate over a vector a from 0 to max_size, but a[i] doesn’t exist as a is initially empty with no elements in it and it might give an error (trying to access a memory that never existed).
So, it is necessary to initialize the vector with a specific size (in your case max_size).

thank you for clearing the doubt

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.