Last active
October 25, 2017 19:50
-
-
Save Demonstrandum/ffb12068a1ff8aaa2d524e89a198cbe3 to your computer and use it in GitHub Desktop.
Prime Sieve, Frost.
This file contains hidden or 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 <stdio.h> | |
#include <stdlib.h> | |
#include <math.h> | |
#define u64 unsigned long long | |
typedef unsigned short int bool; | |
#define false (unsigned short)0 | |
#define true (unsigned short)1 | |
u64 int *sieve(unsigned int upto) | |
{ | |
bool *is_prime = malloc(sizeof(bool) * upto); | |
is_prime[0, 1] = 0; | |
for (int i = 2; i <= upto; i++) | |
is_prime[i] = true; | |
u64 int *primes = malloc(sizeof(u64 int) * upto); | |
for (u64 int i = 2; i < ceil(sqrt(upto)); i++) { | |
for (u64 int j = 2; j < upto; j++) { | |
if (i * j > upto) break; | |
is_prime[i * j] = false; | |
} | |
} | |
unsigned int prime_index = 0; | |
for (u64 int prime = 0; prime <= upto; prime++) { | |
if (is_prime[prime]) { | |
primes[prime_index] = prime; | |
prime_index++; | |
} | |
} | |
free(is_prime); | |
return primes; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
if (argc < 2) { | |
printf("Supply command line argument to choose\n"); | |
printf("which primes to generate under a certain value.\n"); | |
return EXIT_FAILURE; | |
} | |
unsigned int n_primes = atoi(argv[1]); | |
u64 int *primes = sieve(n_primes); | |
u64 int sum = 0; | |
for (u64 int i = 0; i < n_primes; i++) { | |
printf("%lu%s", primes[i], (primes[i + 1] == 0) ? "\n" : ", "); | |
sum += primes[i]; | |
if (primes[i + 1] == 0) break; | |
} | |
printf("Summation of primes down from %u:\n%lu\n", n_primes, sum); | |
free(primes); | |
return EXIT_SUCCESS; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment