Reputation: 41
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;
}
Upvotes: 0
Views: 113
Reputation: 30926
i*j<=100
array index out of bound -- UB...(Undefined Behavior)
It should be i*j<100
.
Upvotes: 3
Reputation: 624
there is an array overflow occurring here
i*j<=100 should be i*j<100
because range of your array is 0-99
Upvotes: 2