Problem 23
C
1#include<stdio.h>
2#include<stdlib.h>
3
4struct sum_nums{
5 int num;
6 struct sum_nums * next;
7};
8
9struct abundant_nums{
10 int abundant_num;
11 struct abundant_nums * next;
12};
13
14struct abundant_nums * head = NULL;
15struct sum_nums * first = NULL;
16
17void add_to_sum_nums(int num){
18 if(first == NULL){
19 first = malloc(sizeof(struct sum_nums));
20 first->num = num;
21 first->next = NULL;
22 }
23 else{
24 struct sum_nums * temp = first;
25 while(temp->next != NULL){
26 temp = temp->next;
27 }
28 temp->next = malloc(sizeof(struct sum_nums));
29 temp->next->num = num;
30 temp->next->next = NULL;
31 }
32}
33
34void add_to_abundant(int num){
35 if(head == NULL){
36 head = malloc(sizeof(struct abundant_nums));
37 head->abundant_num = num;
38 head->next = NULL;
39 }
40 else{
41 struct abundant_nums * temp = head;
42 while(temp->next != NULL){
43 temp = temp->next;
44 }
45 temp->next = malloc(sizeof(struct abundant_nums));
46 temp->next->abundant_num = num;
47 temp->next->next = NULL;
48 }
49}
50void is_abundant(int num){
51 int sum = 0;
52 printf("Current number: %d", num);
53 for(int i = 1; i < num -1; i++){
54 if(num % i == 0){
55 printf("%d\n\n", i);
56 sum += i;
57 }
58 }
59 if(sum > num){
60 printf("%d is abundant\n\n", num);
61 add_to_abundant(num);
62 }
63}
64
65
66void can_be_written_as_sum(int num){
67 struct abundant_nums * temp = head;
68 struct abundant_nums * iterator;
69 int is_sum = 0;
70 while(temp != NULL && is_sum == 0){
71 int difference = num - temp->abundant_num;
72 if(difference > 0){
73 iterator = temp->next;
74 while(iterator != NULL && is_sum == 0){
75 if(iterator->abundant_num == difference){
76 is_sum = 1;
77 }
78 iterator = iterator->next;
79 }
80 }
81 temp = temp->next;
82 }
83 if(is_sum == 0){
84 printf("\n%d cannot be written as sum", num);
85 add_to_sum_nums(num);
86 }
87}
88
89int get_sum(){
90 int sum = 0;
91 struct sum_nums * iterator = first;
92 while(iterator != NULL){
93 sum += iterator->num;
94 iterator = iterator->next;
95 }
96 return sum;
97}
98
99int main(){
100 for(int i = 12; i < 28123; i++){
101 is_abundant(i);
102 }
103
104 for(int i = 24; i < 30000; i++){
105 can_be_written_as_sum(i);
106 }
107
108 printf("Sum of nums %d\n", get_sum());
109}