- #1
kbaumen
- 192
- 0
I do encounter a lot of problems while learning C. For example the code below, I can't understand why doesn't it work. It's meant to print out all primes to 1000 by using the sieve method. However, I only get a blank line. And I've spent about two hours making small modifications and repeatedly rereading the code with no result. Can anyone tell me why doesn't it work?
Here's the code:
Thank you in advance.
Here's the code:
Code:
#include <stdio.h>
#include <stdlib.h>
#define PRIME 1
#define NONPRIME 0
int numbers[1000];
void mark_multiples(int num)
{
int a, j;
a = 0;
j = 2;
while (a < 1000)
{
a = num * j;
if (a >= 1000)
{
break;
}
numbers[a] = NONPRIME;
j++;
}
}
int get_next_prime(int num)
{
int answer;
answer = num + 1;
while (numbers[answer] == NONPRIME)
{
answer++;
if (answer == 1000)
{
break;
}
}
return answer;
}
int main(void)
{
int i, next_prime;
numbers[0] = NONPRIME;
numbers[1] = NONPRIME;
for (i = 2; i < 1000; i++)
{
numbers[i] = PRIME;
}
next_prime = 2;
do
{
mark_multiples(next_prime);
next_prime = get_next_prime(next_prime);
}
while(next_prime < 1000);
for (i = 1; i < 1000; i++);
{
if (numbers[i - 1] == PRIME)
{
printf("%i ", i);
}
}
printf("\n");
return 0;
}
Thank you in advance.
Last edited: