Ian Dorian Macleod
Problem 21
Problem Statement

Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where ab, then a and b are an amicable pair and each of a and b are called amicable numbers.

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.

Evaluate the sum of all the amicable numbers under 10000.

Approach

C++ implementation

#include <stdc++.h>
using namespace std;

int d(int n) {
int ans = 0;
for(int i = 1; i < n; i++) {
if (n % i == 0) ans+=i;
}
return ans;
}

int main() {
vectorcache(10000);
cache = 0;
for(int i = 1; i <= 10000; i++) {
cache[i] = d(i);
}
long long int ans = 0;
for(int i = 1; i <= 10000; i++) {
for(int j = i+1; j <= 10000; j++) {
if (cache[i] == j && cache[j] == i) ans = ans + i + j;
}
}
cout << ans << endl;
return 0;
}


You can also download the source code for this problem here and compile it on your local machine.
Further Analysis