Last active
January 16, 2019 00:33
-
-
Save mizhi/ebf24899e454c2218d8ed77e88a02e38 to your computer and use it in GitHub Desktop.
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
| /* *=== Tuesday Jan 15th 2019 - Daily Programmer ===* | |
| *[Sum of Primes]* | |
| The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. | |
| Find the sum of all the primes below two million. | |
| */ | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #define MAX_N 2000000 | |
| int* make_sieve(); | |
| int main(int argc, char** argv) { | |
| int *sieve = make_sieve(); | |
| int idx = 2; | |
| while (idx <= MAX_N) { | |
| for ( ; idx <= MAX_N && sieve[idx] == 0; idx++); | |
| for (int p = idx + idx; p <= MAX_N; p += idx) sieve[p] = 0; | |
| idx++; | |
| } | |
| long sum = 0; | |
| for (int i = 2; i <= MAX_N; i++) sum += sieve[i]; | |
| printf("%li\n", sum); | |
| free(sieve); | |
| return 0; | |
| } | |
| int* make_sieve() { | |
| int* sieve = (int*)malloc(sizeof(int) * (MAX_N + 1)); | |
| for (int i = 0; i <= MAX_N; i++) sieve[i] = i; | |
| return sieve; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment