Algorithms_in_C 1.0.0
Set of algorithms implemented in C.
Loading...
Searching...
No Matches
sol2.c File Reference

Problem 10 solution More...

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
Include dependency graph for sol2.c:

Functions

int main (int argc, char *argv[])
 Main function.
 

Detailed Description

Problem 10 solution

Author
Krishna Vedala

Function Documentation

◆ main()

int main ( int  argc,
char *  argv[] 
)

Main function.

12{
13 long n = 100;
14 long long sum = 0;
15 char *sieve = NULL;
16
17 if (argc == 2) /* if command line argument is provided */
18 n = atol(argv[1]); /* use that as the upper limit */
19
20 /* allocate memory for the sieve */
21 sieve = calloc(n, sizeof(*sieve));
22 if (!sieve)
23 {
24 perror("Unable to allocate memory!");
25 return -1;
26 }
27
28 /* build sieve of Eratosthenes
29 In the array,
30 * if i^th cell is '1', then 'i' is composite
31 * if i^th cell is '0', then 'i' is prime
32 */
33 for (long i = 2; i < sqrtl(n); i++)
34 {
35 /* if i^th element is prime, mark all its multiples
36 as composites */
37 if (!sieve[i])
38 {
39 for (long j = i * i; j < n + 1; j += i)
40 {
41 sieve[j] = 1;
42 }
43 sum += i;
44 }
45 }
46
47 for (long i = sqrtl(n) + 1; i < n; i++)
48 if (!sieve[i])
49 sum += i;
50
51 free(sieve);
52
53 printf("%ld: %lld\n", n, sum);
54
55 return 0;
56}
#define free(ptr)
This macro replace the standard free function with free_dbg.
Definition malloc_dbg.h:26
#define calloc(elemCount, elemSize)
This macro replace the standard calloc function with calloc_dbg.
Definition malloc_dbg.h:22