Created
April 22, 2011 09:20
-
-
Save zrbecker/936329 to your computer and use it in GitHub Desktop.
Euler 10
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> | |
| typedef unsigned long ul; | |
| ul *maxprimeslist(ul max, int *found) { | |
| int cprimes = 10; | |
| ul *primes = (ul *)malloc(cprimes * sizeof(ul)); | |
| int nprimes = 0; | |
| int i, j, prime; | |
| for (i = 2; i < max; ++i) { | |
| prime = 1; | |
| ul max = (ul)sqrt((double)i); | |
| for (j = 0; j < nprimes; ++j) { | |
| if (max < primes[j]) | |
| break; | |
| if (i % primes[j] == 0) { | |
| prime = 0; | |
| break; | |
| } | |
| } | |
| if (prime) { | |
| ++nprimes; | |
| if (nprimes >= cprimes) { | |
| cprimes *= cprimes; | |
| primes = (ul *)realloc(primes, cprimes * sizeof(ul)); | |
| } | |
| primes[nprimes - 1] = i; | |
| } | |
| } | |
| *found = nprimes; | |
| return primes; | |
| } | |
| int main(int argc, char **argv) { | |
| if (argc != 2) { | |
| printf("Wrong!\n"); | |
| return 1; | |
| } | |
| ul n = strtoul(argv[1], NULL, 0); | |
| int found; | |
| ul *primes = maxprimeslist(n, &found); | |
| ul sum = 0; | |
| ul i; | |
| for (i = 0; i < found; ++i) { | |
| sum += primes[i]; | |
| } | |
| free(primes); | |
| printf("Sum: %lu\n", sum); | |
| return 0; | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment