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;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "primes.h"
|
||||
|
||||
#define MAX_NUM 100000000
|
||||
@@ -13,6 +14,7 @@ int main(int argc, char **argv)
|
||||
long sum = 0;
|
||||
char *primes;
|
||||
|
||||
/*
|
||||
primes = malloc((MAX_NUM+1)*sizeof(char));
|
||||
for (i=1; i<MAX_NUM+1; i++) {
|
||||
if (is_prime(i)) {
|
||||
@@ -21,6 +23,12 @@ int main(int argc, char **argv)
|
||||
primes[i] = FALSE;
|
||||
}
|
||||
}
|
||||
*/
|
||||
primes = eratosthenes(MAX_NUM);
|
||||
if (primes == NULL) {
|
||||
printf("Error");
|
||||
return 1;
|
||||
}
|
||||
|
||||
for(i=1; i<MAX_NUM; i++) {
|
||||
match = TRUE;
|
||||
|
||||
Reference in New Issue
Block a user