Skip to content

Instantly share code, notes, and snippets.

@sidsbrmnn
Created August 15, 2021 10:08
Show Gist options
  • Save sidsbrmnn/35cfa49094847a86be2377eef4594bda to your computer and use it in GitHub Desktop.
Save sidsbrmnn/35cfa49094847a86be2377eef4594bda to your computer and use it in GitHub Desktop.
C implementation of the Sieve of Eratosthenes to finding all prime numbers up to any given limit.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int *sieve_of_eratosthenes(const int n) {
int *primes = (int *)malloc(sizeof(int) * (n + 1));
for (int i = 0; i < n + 1; i++) {
primes[i] = 1;
}
primes[0] = 0;
primes[1] = 0;
for (int i = 0; i < sqrt(n); i++) {
if (primes[i] != 0) {
for (int j = i * i; j < n + 1; j += i) {
primes[i] = 0;
}
}
}
return primes;
}
int main(int argc, char const **argv) {
int *primes = sieve_of_eratosthenes(121);
for (int i = 0; i < 122; i++) {
if (primes[i] != 0) {
printf("%d ", i);
}
}
printf("\n");
free(primes);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment