Question

I wrote the following program to display all prime numbers up to 150. It is not executing at all. what is so wrong with it?

# include <stdio.h>
int main(void)
{
    int p[150], i, j;

    for (i = 2; i < 150; i++)
        p[i] = 0;

    i = 2;


    while (i < 150){

        if (p[i] == 0)
            printf("%i ", i);

        for (j = 1; i*j <= 150; j++)
            p[i*j] = 1;

        i++;
    }

    return 0;
}
Était-ce utile?

La solution 2

i*j <= 150 is incorrect, it should be i*j < 150, because the p array has elements from 0 to 149. The program gets stuck in an infinite loop because of this.

EDIT: The rest of this answer was incorrect, so I've removed it.

Autres conseils

  1. You're accessing p[i*j], which is beyond the valid [0-149] range. The condition i*j <= 150 will evaluate true when i*j is equal to 150, which is off-by-one. It should be i*j < 150.
  2. The stdout stream is buffered. You need to flush at the end of your loop. Try adding a fflush(stdout).
  3. Might be of less importance, but if you care about the resulting array (e.g.: wants to use it later), the value of p[2] is erroneously set to 1. However, your program would still print 2, but that's because your loop prints numbers before changing the value of p[i*j]. Concluding, numbers get printed correctly, but the values in the array are not entirely correct.

As a learning exeercise, try adding some printf's to learn what your program does.

Also bear in mind that, as jweyrich says, that printf without \n in it will not output anything until (possibly) the program exits.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top