Finding primes not using % sign.

Here are the instructions, I just wanted to know if what I have down is correct.
I read the code over and over and it seems correct. I just wanted some input.

Thanks.

1
2
3
4
5
6
1. Create an array with length n. 
2. Mark each item in your array with a marker that indicates that the index is a prime number. 
4. Set p to 2.
5. While p is less than the square root of n:
    o Change the markers at every pth index to indicate non-primeness.
    o Advance p to the next place in the array that is marked as prime.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void findPrimes(vector<int>& primes, int n) {     
     int array[n];
     int prime = 1; 
     int p = 2;  
     
     for (2 <= sqrt(n); p++;)
         array[p] = prime;
          
     for(p <= sqrt(n); p++){
           if(p != 0)
           for (int q=p; q <= sqrt(n); q+p){
               array[q+p] = 0;
             }
           else
           continue;            
             }
Look in to while loops, they're better suited for this, I think.
http://www.cplusplus.com/doc/tutorial/control/
cipher, a for loop and a while loop are the same thing, really.
Thanks for the suggestion, but I am required to use for loops.
Syntax
1
2
for( initialisation; condition; increment )
  statement;

I don't understand.
_Do you get the primes below n or below sqrt(n) ? You loop till sqrt(n) but your array is size n.
_if(p != 0) ? how could p be zero?
Due to the condition 2 <= sqrt(n), the first loop is either never executed or repeated forever.
Same for the third loop. q+p doesn't actually do anything, so the loop never advances. The condition is wrong too, you need to go all the way to n.
Instead of an int array, you should use a vector<bool>. That will cut your memory requirements by a factor of 32.
More importantly, you can't have a variable as an array size, it must be a constant expression known at compile-time.
Last edited on
Topic archived. No new replies allowed.