J
Joel Mayes
Hi All;
I'm teaching myself C, and have written a prime number generator. It is
a pretty inefficient implementation of the Sieve of Eratosthenes to
calculate primes up to 1,000,000. If anyone has time to critic and offer
my some feedback I'd be grateful
Thanks
Joel
#include<stdio.h>
#include<math.h>
#define MAXCOUNT 1000000
int main(void) {
int search_array[MAXCOUNT];
int count;
int prime = 2; /* initialize prime as a prime */
int nextprime = 0;
int counter = 0;
int stop = 0;
/* Initialize the searching array from 1 -> MAXCOUNT */
for ( count = 2; count <= MAXCOUNT; count++ ) {
search_array[ count ] = count;
}
do {
for ( count = prime * 2 ; count <= MAXCOUNT; count = count + prime ) {
search_array[count] = 0;
}
counter = prime + 1;
nextprime = 0;
stop = 0;
do {
if ( search_array[counter] != 0 ) {
nextprime = search_array[counter];
stop = 0;
}
else {
counter++;
if ( pow(counter, 2) > MAXCOUNT ) {
stop = 1;
}
}
} while( counter < MAXCOUNT && nextprime == 0);
prime = nextprime;
if (prime != 0) {
printf("%d ", prime);
}
} while( stop == 0 );
return 0;
}
I'm teaching myself C, and have written a prime number generator. It is
a pretty inefficient implementation of the Sieve of Eratosthenes to
calculate primes up to 1,000,000. If anyone has time to critic and offer
my some feedback I'd be grateful
Thanks
Joel
#include<stdio.h>
#include<math.h>
#define MAXCOUNT 1000000
int main(void) {
int search_array[MAXCOUNT];
int count;
int prime = 2; /* initialize prime as a prime */
int nextprime = 0;
int counter = 0;
int stop = 0;
/* Initialize the searching array from 1 -> MAXCOUNT */
for ( count = 2; count <= MAXCOUNT; count++ ) {
search_array[ count ] = count;
}
do {
for ( count = prime * 2 ; count <= MAXCOUNT; count = count + prime ) {
search_array[count] = 0;
}
counter = prime + 1;
nextprime = 0;
stop = 0;
do {
if ( search_array[counter] != 0 ) {
nextprime = search_array[counter];
stop = 0;
}
else {
counter++;
if ( pow(counter, 2) > MAXCOUNT ) {
stop = 1;
}
}
} while( counter < MAXCOUNT && nextprime == 0);
prime = nextprime;
if (prime != 0) {
printf("%d ", prime);
}
} while( stop == 0 );
return 0;
}