Hi there, I have a problem with a seemingly simple C program that is meant to produce prime numbers up to a desired amount.
However, the program I've made doesn't produce them past 3 - as in I run the program and set the number to 10 and only the numbers 2 and 3 are displayed.
It is meant to use the Sieve of Eratosthenes to calculate prime numbers up to (but not including) N.
This is the code:
[code]#include <stdio.h>
#include <stdlib.h>
int main()
{
int N, i, j;
int *a;
printf("How much? "); scanf("%i", &N);
a = (int*) malloc(N * sizeof(int));
for(i=2;i<N;i++) {
a[i] = 1;
}
for(i=2;i<N;i++)
if(a[i] == 1)
for(j=i+i;j<N;j++)
a[j] = 0;
for(i=2;i<N;i++)
if(a[i] == 1)
printf("%i ", i);
printf("\n");
}[/code]
I would appreciate any help on this. Thanks.
You need to increment j by i so that j is always divisible by i.
[code]for (j=i+i; j<N; j+=i)[/code]
Adding some comments and/or descriptive variable names would be helpful for future problems.
Sorry, you need to Log In to post a reply to this thread.