Skip to content

Instantly share code, notes, and snippets.

@aprell
Created July 10, 2013 18:27
Show Gist options
  • Select an option

  • Save aprell/5968811 to your computer and use it in GitHub Desktop.

Select an option

Save aprell/5968811 to your computer and use it in GitHub Desktop.
Prime sieve using queues
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "queue.h"
static int *numbers;
Queue *generate(int n)
{
Queue *input = queue_new();
int i;
// Initial input is a queue of numbers from 2 to n
for (i = 2; i <= n; i++) {
numbers[i] = i;
queue_enqueue(input, &numbers[i]);
}
return input;
}
Queue *sieve(Queue *input)
{
Queue *output;
int *n, prime;
if (queue_empty(input)) {
// End of recursion
free(input);
return NULL;
}
// First element of input is prime
prime = *(int *)queue_dequeue(input);
printf("%2d is prime\n", prime);
output = queue_new();
while ((n = (int *)queue_dequeue(input)) != NULL) {
// Remove all multiples of prime; those are not prime
if (*n % prime != 0) {
queue_enqueue(output, n);
}
}
assert(queue_empty(input));
free(input);
return sieve(output);
}
int main(int argc, char *argv[])
{
int n;
if (argc != 2 || (n = atoi(argv[1])) < 2) {
printf("Usage: %s <upper limit>\n", argv[0]);
return 0;
}
numbers = malloc((n+1) * sizeof(int));
if (!numbers) {
fprintf(stderr, "Out of memory\n");
return 1;
}
sieve(generate(n));
free(numbers);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment