Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*
* % gcc -O3 -std=c99 -o sum sum.c; ./sum
* sum:142913828922,count:148933,cpu:0.00
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#define LAST_NR 2000000
#define PRIME 0
#define NOT_PRIME 1
int main()
{
clock_t before = clock(), after;
float spent;
char status[LAST_NR];
uint64_t sq = 1 + (uint64_t) sqrt(LAST_NR), count = 0, ret;
uint64_t sum = 0;
memset(status, PRIME, LAST_NR);
for (uint64_t i = 2; i <= sq; i++)
if (status[i] == PRIME) {
sum += i;
count++;
for (uint64_t j = 2 * i; j <= LAST_NR; j += i)
status[j] = NOT_PRIME;
}
for (uint64_t i = sq + 1; i <= LAST_NR; i++)
if (status[i] == PRIME) {
sum += i;
count++;
}
after = clock();
spent = (float) (after - before) / (float) CLOCKS_PER_SEC;
ret = printf("sum:%li,count:%li,cpu:%.2f\n", sum, count, spent);
return (ret > 0) ? EXIT_SUCCESS : EXIT_FAILURE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.