Created
August 15, 2021 10:08
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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