Printing primes using the seive method

I have to write a code that prints prime numbers by using the seive of Eratosthenes. I have a Borland compiler and can't seem to get this code working. No errors remain although instead of printing prime numbers, the output is a random sequence of numbers and letters. The specifications required were that there had to be three functions other than the main. One was a strike off function that made all of the composite numbers true(the Boolean method had to be used along with an array). The other was a count off function that counted by each number to be sent to the strike function and be labeled as composite. My final function's job was to print prime numbers.

Here is a look at my three functions :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
void strike(int l, int n) {  //l is the value of each element in the array

//purpose: strikes out all multiples of n

int j; //used to find multiples

for (j=n; j*n<k; j++) {
        if (n*j==l) {
                stuff[l]=true; //l is composite if it can be a product of two different numbers
                }
        }
}

void count(int l, int n) {

//Counts by numbers to send to the strike function to find composites

for (n=2; n*n<k; n++) {  //starts out by counting by two then continues to three and so on
        if (stuff[l]==false) {
                strike(l,n); //if strike misses a number, this makes the loop repeat
                }
        }
}

void print(int l) {
// prints primes
// l is the value of the location of the primes  
for (l=2; l<k; l++) {
        if (stuff[l]==false) {
                cout << l; // if l is prime, it prints l
                }
        }
}

I would like some advice on why the output is a random bunch of numbers and letters. However, this is an assignment for school so I would only like to have some reference and not have someone write my code for me. Thank you.
Last edited on
i don't understand variable l. you don't appear to need it in count() or strike(). and in print() you overwrite it right away.

in strike(), n*j is always a mutliple, so what are you checking l for? the stuff[] for all the multiples should be made true, right?

in count(), you loop through all the numbers, but you always check the same stuff[l]. maybe as variable n changes you ought to check the stuff[] for the new n? same thing for calling strike().

have you set all your stuff[] to a starting value (false, i guess?)? i don't see that here, but you may do that somewhere before count().


other than that, it looks like it just might work!

starting the strike at the square is neat. the earlier numbers were already checked.
Thank you for your comments. You were right, I did make stuff[] false before my functions. I understand now that the variable l has no purpose in the first two functions. Thanks again for your advice.
Topic archived. No new replies allowed.