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

Problem 21 solution More...

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
Include dependency graph for sol1.c:

Functions

unsigned long sum_of_divisors (unsigned int N)
 function to return the sum of proper divisors of N
 
int main (int argc, char **argv)
 Main function.
 

Detailed Description

Problem 21 solution

Author
Krishna Vedala

Function Documentation

◆ main()

int main ( int  argc,
char **  argv 
)

Main function.

37{
38 unsigned long sum = 0;
39 unsigned int MAX_N = 500;
40 if (argc == 2)
41 MAX_N = atoi(argv[1]);
42
43 /*
44 * We use an array of flags to check if a number at the index was:
45 * not-processed = 0
46 * is amicable = 1
47 * not amicable = -1
48 */
49 char *flags = (char *)calloc(MAX_N, sizeof(char));
50
51 clock_t start_time = clock();
52 int i;
53 /* there are no such numbers till 10. Lets search from there on */
54 for (i = 10; i < MAX_N; i++)
55 {
56 if (flags[i] != 0)
57 /* already processed, skip */
58 continue;
59
60 unsigned int b = sum_of_divisors(i);
61 if (b >= MAX_N)
62 flags[i] = -1;
63 else if (flags[b] == -1)
64 continue;
65
66 unsigned int c = sum_of_divisors(b);
67 if (c == i && b != i)
68 {
69 /* found amicable */
70 flags[b] = 1;
71 flags[i] = 1;
72 sum += b + i;
73#ifdef DEBUG
74 printf("Amicable: %4d : %4d\n", i, b);
75#endif
76 }
77 else
78 {
79 flags[i] = -1;
80 if (b < MAX_N)
81 flags[b] = -1;
82 }
83 }
84
85 clock_t end_time = clock();
86
87 printf("\nTime taken: %.4g millisecond\n",
88 1e3 * (end_time - start_time) / CLOCKS_PER_SEC);
89 printf("Sum of all numbers = %lu\n", sum);
90
91 free(flags);
92 return 0;
93}
#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
unsigned long sum_of_divisors(unsigned int N)
function to return the sum of proper divisors of N
Definition sol1.c:13
Here is the call graph for this function:

◆ sum_of_divisors()

unsigned long sum_of_divisors ( unsigned int  N)

function to return the sum of proper divisors of N

14{
15 unsigned long sum = 1 + N; /* 1 and itself are always a divisor */
16 /* divisors are symmertically distributed about the square-root */
17 for (unsigned int i = 2; i * i < N; i++)
18 {
19 if ((N % i) != 0)
20 /* i is not a divisor of N */
21 continue;
22
23 // #ifdef DEBUG
24 // printf("%4d, %4d,", i, N / i);
25 // #endif
26
27 sum += i + (N / i);
28 }
29 // #ifdef DEBUG
30 // printf("\nSum of divisors of %4d: %4d\n", N, sum);
31 // #endif
32 return sum;
33}