2020-06-05 19:20:25 +03:00
|
|
|
/**
|
|
|
|
* \file
|
|
|
|
* \brief [Problem 10](https://projecteuler.net/problem=10) solution
|
2020-06-06 21:51:49 +03:00
|
|
|
* \author [Krishna Vedala](https://github.com/kvedala)
|
2020-06-05 19:20:25 +03:00
|
|
|
*/
|
2020-03-30 05:21:49 +03:00
|
|
|
#include <math.h>
|
2020-05-29 23:23:24 +03:00
|
|
|
#include <stdio.h>
|
2020-03-30 05:21:49 +03:00
|
|
|
#include <stdlib.h>
|
|
|
|
|
2020-06-05 19:20:25 +03:00
|
|
|
/** Main function */
|
2020-05-29 23:23:24 +03:00
|
|
|
int main(int argc, char *argv[])
|
2020-03-30 05:21:49 +03:00
|
|
|
{
|
|
|
|
long n = 100;
|
|
|
|
long long sum = 0;
|
|
|
|
char *sieve = NULL;
|
|
|
|
|
2020-05-29 23:23:24 +03:00
|
|
|
if (argc == 2) /* if command line argument is provided */
|
|
|
|
n = atol(argv[1]); /* use that as the upper limit */
|
2020-03-30 05:21:49 +03:00
|
|
|
|
|
|
|
/* allocate memory for the sieve */
|
|
|
|
sieve = calloc(n, sizeof(*sieve));
|
2020-05-29 23:23:24 +03:00
|
|
|
if (!sieve)
|
2020-03-30 05:21:49 +03:00
|
|
|
{
|
|
|
|
perror("Unable to allocate memory!");
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
|
2020-05-29 23:23:24 +03:00
|
|
|
/* build sieve of Eratosthenes
|
|
|
|
In the array,
|
2020-03-30 05:21:49 +03:00
|
|
|
* if i^th cell is '1', then 'i' is composite
|
|
|
|
* if i^th cell is '0', then 'i' is prime
|
|
|
|
*/
|
2020-05-29 23:23:24 +03:00
|
|
|
for (long i = 2; i < sqrtl(n); i++)
|
2020-03-30 05:21:49 +03:00
|
|
|
{
|
|
|
|
/* if i^th element is prime, mark all its multiples
|
|
|
|
as composites */
|
2020-05-29 23:23:24 +03:00
|
|
|
if (!sieve[i])
|
|
|
|
{
|
|
|
|
for (long j = i * i; j < n + 1; j += i)
|
2020-03-30 05:21:49 +03:00
|
|
|
{
|
|
|
|
sieve[j] = 1;
|
|
|
|
}
|
2020-03-30 06:20:41 +03:00
|
|
|
sum += i;
|
2020-03-30 05:21:49 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-29 23:23:24 +03:00
|
|
|
for (long i = sqrtl(n) + 1; i < n; i++)
|
2020-03-30 05:21:49 +03:00
|
|
|
if (!sieve[i])
|
|
|
|
sum += i;
|
|
|
|
|
|
|
|
free(sieve);
|
2020-05-29 23:23:24 +03:00
|
|
|
|
2020-03-30 05:21:49 +03:00
|
|
|
printf("%ld: %lld\n", n, sum);
|
|
|
|
|
|
|
|
return 0;
|
2020-06-06 21:51:49 +03:00
|
|
|
}
|