Add sieve of eratosthenes

This commit is contained in:
Kevin Keogh
2019-03-18 15:20:29 -04:00
parent fe204db23c
commit 0551709888
2 changed files with 35 additions and 0 deletions

View File

@@ -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;
}

View File

@@ -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;