Problem 21
Ruby
1def get_proper_divisors(num)
2 list = (1..num - 1).to_a
3 divisors = []
4 list.map{|n| if num % n == 0
5 divisors.push(n)
6 end}
7 divisors.reduce(:+)
8end
9
10def is_amicable(num)
11 a = get_proper_divisors(num)
12 b = get_proper_divisors(a)
13 if a != b
14 if b == num
15 true
16 else
17 false
18 end
19 end
20end
21
22amicable = []
23(220..9999).to_a.map{|n| if is_amicable(n) == true
24 amicable.push(n)
25end}
26puts amicable.reduce(:+)
1#include<stdio.h>
2#include<math.h>
3#include<stdlib.h>
4
5struct pair_am_num{
6 int a;
7 int b;
8 struct pair_am_num * next;
9};
10
11struct num_exists{
12 int num;
13 struct num_exists * next;
14};
15
16struct pair_am_num * head = NULL;
17struct num_exists * tracker = NULL;
18int d(int num){
19 int sum = 0;
20 printf("%d\n", num);
21 for(int i = 2; i <num; i++){
22 if(num % i == 0){
23 printf("adding %d\n", i);
24 sum += i;
25 }
26 }
27 sum++; //include 1
28 return sum;
29}
30
31void add_to_am_num(int a, int b){
32 if(head == NULL){
33 head = malloc(sizeof(struct pair_am_num));
34 head->a = a;
35 head->b = b;
36 head->next = NULL;
37 }
38 else{
39 struct pair_am_num * temp = head;
40 while(temp->next != NULL){
41 temp = temp->next;
42 }
43 temp->next = malloc(sizeof(struct pair_am_num));
44 temp->next->a = a;
45 temp->next->b = b;
46 temp->next->next = NULL;
47 }
48}
49
50int does_exist(int num){
51 if(tracker == NULL){
52 tracker = malloc(sizeof(struct num_exists));
53 tracker->num = num;
54 tracker->next = NULL;
55 return 0;
56 }
57 else{
58 struct num_exists * temp = tracker;
59 while(temp->next != NULL){
60 if(temp->num == num){
61 return 1;
62 }
63 temp = temp->next;
64 }
65 temp->next = malloc(sizeof(struct num_exists));
66 temp->next->next = NULL;
67 temp->next->num = num;
68 return 0;
69 }
70}
71
72void get_pairs(){
73 int b;
74 for (int a = 1; a <= 10000; a++){
75 b = d(a);
76 printf("a: %d\n\nComparing %d and %d \n",a, b, d(b));
77 if(d(b) == a && does_exist(a) == 0 && does_exist(b) == 0){
78 add_to_am_num(a, b);
79 }
80 }
81}
82
83int get_sum(){
84 get_pairs();
85 struct pair_am_num * temp = head;
86 int sum = 0;
87 while(temp != NULL){
88 sum = sum + temp->a + temp->b;
89 temp = temp->next;
90 }
91 return sum;
92}
93
94int main(){
95 printf("%d\n\n", get_sum());
96 return 0;
97}