The 21th Project Euler problem - Amicable Numbers - is stated as follows. Evaluate the sum of all the amicable numbers under 10000.
const getProperDivisors = (n) => {
const divisors = [];
const root = Math.floor(Math.sqrt(n));
for (let i = 1; i <= root; i++) {
if (n % i === 0) {
divisors.push(i);
if (Math.pow(i, 2) !== n) {
divisors.push(n / i);
}
}
}
return divisors.sort(function (a, b) {
return a - b;
}).filter(x => x !== n);
};
// Let d(n) be defined as the sum of proper divisors of
// n (numbers less than n which divide evenly into n).
const d = (n) => {
const divisors = getProperDivisors(n);
return divisors.reduce((a,b) => a + b, 0);
};
// Iterate over all numbers from 0 to 9999.
const result = Array.from({length: 9999}).map((_, n) => {
const a = d(n);
const b = d(a);
// If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable
// pair and each of a and b are called amicable numbers.
return n !== a && n === b ? a : 0;
}).reduce((a,b) => a + b);