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 04:56:12 +03:00
|
|
|
#include <math.h>
|
2020-05-29 23:23:24 +03:00
|
|
|
#include <stdio.h>
|
2020-03-30 04:56:12 +03:00
|
|
|
#include <stdlib.h>
|
|
|
|
|
2020-06-05 19:20:25 +03:00
|
|
|
/** Function to check if a number is prime */
|
|
|
|
char is_prime(unsigned long n)
|
2020-03-30 04:56:12 +03:00
|
|
|
{
|
2020-06-05 19:20:25 +03:00
|
|
|
for (unsigned long i = 2; i < sqrtl(n) + 1; i++)
|
2020-05-29 23:23:24 +03:00
|
|
|
if (n % i == 0)
|
2020-03-30 04:56:12 +03:00
|
|
|
return 0;
|
|
|
|
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2020-06-05 19:20:25 +03:00
|
|
|
/** Computes sum of prime numbers less than N */
|
|
|
|
unsigned long long sum_of_primes(unsigned long N)
|
2020-03-30 04:56:12 +03:00
|
|
|
{
|
2020-06-05 19:20:25 +03:00
|
|
|
unsigned long long sum = 2;
|
2020-03-30 04:56:12 +03:00
|
|
|
|
2020-05-29 23:23:24 +03:00
|
|
|
for (long i = 3; i < N; i += 2) /* skip even numbers */
|
2020-03-30 04:56:12 +03:00
|
|
|
if (is_prime(i))
|
|
|
|
sum += i;
|
|
|
|
|
|
|
|
return sum;
|
|
|
|
}
|
|
|
|
|
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 04:56:12 +03:00
|
|
|
{
|
2020-06-05 19:20:25 +03:00
|
|
|
unsigned long n = 100;
|
2020-03-30 04:56:12 +03:00
|
|
|
|
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 04:56:12 +03:00
|
|
|
|
2020-06-05 19:20:25 +03:00
|
|
|
printf("%ld: %llu\n", n, sum_of_primes(n));
|
2020-03-30 04:56:12 +03:00
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|