Add sieve of eratosthenes
This commit is contained in:
27
primes.h
27
primes.h
@@ -1,3 +1,8 @@
|
||||
#include <stdlib.h>
|
||||
|
||||
#define TRUE 1
|
||||
#define FALSE 0
|
||||
|
||||
int is_prime(long num)
|
||||
{
|
||||
int i = 5;
|
||||
@@ -19,3 +24,25 @@ int is_prime(long num)
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
char* eratosthenes(long num)
|
||||
{
|
||||
long i, j;
|
||||
char* primes;
|
||||
|
||||
primes = (char*)malloc((num+1)*sizeof(char));
|
||||
if (primes == NULL) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
memset(primes, TRUE, num);
|
||||
primes[1] = FALSE;
|
||||
|
||||
for (i=2; i<=num; i++)
|
||||
if (primes[i])
|
||||
/* Mark factors as composite */
|
||||
for (j=i*i; j<num; j+=i)
|
||||
primes[j] = FALSE;
|
||||
|
||||
return primes;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user