/* Simple Sieve of Eratosthenes microbenchmark. */ #include #include #include void mark_off(char *is_composite, int p, int max) { for (int i = p * p; i < max; i += p) is_composite[i] = 1; } int main(int argc, char **argv) { int max; if (argc != 2 || (max = atoi(argv[1])) == 0) { fprintf(stderr, "Usage: %s 53\n" "Prints the last prime number before 53\n", argv[0]); return -1; } char *is_composite = malloc(max); if (!is_composite) { perror("malloc"); return 1; } memset(is_composite, 0, max); mark_off(is_composite, 2, max); for (int i = 3; i * i < max; i += 2) { if (!is_composite[i]) mark_off(is_composite, i, max); } for (int p = max-1; p > 1; p--) { if (is_composite[p]) continue; printf("%d\n", p); break; } return 0; }