Skip to content

Commit

Permalink
Fix sieve.c and make it faster
Browse files Browse the repository at this point in the history
  • Loading branch information
tommythorn committed Sep 18, 2023
1 parent d7d05ae commit badea83
Showing 1 changed file with 31 additions and 19 deletions.
50 changes: 31 additions & 19 deletions examples/sieve.c
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,40 @@
// for (..)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main(int argc, char **argv) {
int N, p, j;
char *excluded, *excluded_end, *cp;

N = 10000;
excluded = malloc(N);
excluded_end = excluded + N;
memset(excluded, 0, N);

p = 2;
while (p < N) {
if (!excluded[p]) {
printf(" %d", p);
j = p*2;
cp = excluded + j;
while (cp < excluded_end) {
*cp = 1;
cp = cp + j;
}
int N, j, p;
char *primes, *primes_end, *cp, *pi;

N = 1000;
// 3 5 7 9 11 13 .. i*2+3
// primes[N] is a sential 0; this enables us to scan without
// having to test against the array limit
primes = malloc(N+1);
primes_end = primes + N;
memset(primes, 1, N + 1);

printf("2");

pi = primes;
while (pi < primes_end) {
p = 3 + 2*(pi - primes);
printf(" %d", p);
cp = pi + p;
while (cp < primes_end) {
*cp = 0; // Sieve out multiples of p
cp = cp + p;
}
++p;

++pi;
while (!*pi)
++pi;
}

printf("\n");

return 0;
}

0 comments on commit badea83

Please sign in to comment.