Reputation: 25
I am a beginner in C and was working on a program that can output the prime numbers within the range using Eratosthenes' sieve. However, the program does not output anything and is in a loop, I believe this has to do with the repetitive use of for statements in my code but also have no idea where I may be going wrong. I tried putting break statements with if statements but it seems like it does not work. Thank you in advance.
#include <stdio.h>
#include <math.h>
int sieve(int limit);
int main() {
int maximum = 0;
printf("Enter the limit of prime numbers:");
scanf_s("%d", &maximum);
sieve(maximum);
return 0;
}
int sieve(int limit) {
int array[100];
int common = 2;;
for (int i = 0; i <= limit; i++) {
array[i] = i + 1;
}
for (;;) {
for (int j = 0; j <= limit; j++) {
if (array[j] % common == 0 && !(array[j] == common)) {
array[j] = 0;
array[0] = 0;
}
}
for (int k = 0; k <= limit; k++) {
if (!(array[k] == 0) && !(common == array[k])) {
common = array[k];
break;
}
}
if (common >= sqrt(limit))
break;
}
for (int o = 0; o < limit; o++) {
if (!(array[o] == 0)) {
printf("%d ", array[o]);
}
}
return 0;
}
Upvotes: 2
Views: 150
Reputation: 144770
The outer loop runs for ever because you do not increment common
inside the loop body.
Note also that you can enumerate all multiples of common
with a simple addition instead of a costly %
operator.
Here is a modified version:
#include <stdio.h>
int sieve(int limit);
int main() {
int maximum = 0;
printf("Enter the limit of prime numbers:");
scanf_s("%d", &maximum);
sieve(maximum);
return 0;
}
int sieve(int limit) {
int array[limit + 1];
for (int i = 0; i <= limit; i++) {
array[i] = i;
}
for (int common = 2; common * common <= limit; common++) {
// remove all multiples of common. Start at common*common
// because lesser multiples have already been removed as they
// are multiples of a smaller number
for (int i = common * common; i <= limit; i += common) {
array[i] = 0;
}
}
for (int i = 1; i <= limit; i++) {
if (array[i] != 0) {
printf("%d ", array[i]);
}
}
printf("\n");
return 0;
}
Note that you can use an array of unsigned char
initialized to 1
and print i
instead of array[i]
.
Upvotes: 1
Reputation: 56
I hope I'm not out of my depth here since it's been a while since I have touched C.
You could set a boolean variable to false. Within the child loop you set it to true. Add an if statement within the parent loop to check if that variable is true and break the parent loop if it is.
Quick pseudo-code:
bool t = false
parent loop:
child loop:
if something
t = true
if t
break
Upvotes: 2