Sieve of Eratosthenes algorithm - works fine but crashes after

132 views Asked by At

newbie here:

the following program to generate all prime numbers under 100 using the "Sieve of Eratosthenes algorithm" works fine, but crashes after displaying the CORRECT output!

the error in windows: primenumber.exe has stopped working!

#include<stdio.h>
int main()
{
  int P[100] = {0}, i, j;

  for(i = 2; i < 100; ++i)
  {
    if(P[i] == 0)
      printf("%d\n", i);

    for(j = 1; i * j <= 100; ++j)
      P[i * j] = 1;
  }

  return 0;
}
2

There are 2 answers

0
user2736738 On BEST ANSWER

i*j<=100 array index out of bound -- UB...(Undefined Behavior)

It should be i*j<100.

0
kapil On

there is an array overflow occurring here

 i*j<=100 should be i*j<100

because range of your array is 0-99