Project Euler Problem 23 - riemann79/hello-world GitHub Wiki
function propers(n) {
var divs = [];
for(var i = 1; i < n; i++) {
if(n%i === 0) {
divs.push(i);
}
}
return divs;
}
function abundant(n) {
var divs = propers(n);
var sum = 0;
for(var i = 0; i < divs.length; i++) {
sum += divs[i];
}
return sum > n;
}
var candidates = {}; // Integers that potentially cannot be written as the sum of two abundant numbers
var abundants = []; // Abundant numbers
// The range of integers is [1, 28123] because every number greater than
// 28123 can be written as the sum of two abundant numbers.
for(i = 1; i < 28123; i++) {
candidates[i] = false;
if(abundant(i)) {
abundants.push(i);
}
}
var sum = 0;
var n = abundants.length;
for(i = 0; i < n; i++) {
for(var j = n-1; j >= i; j--) {
var s = abundants[i] + abundants[j];
// If the sum of two abundant falls in the range, then the number can be written
// as the sum of two abundant numbers.
if(s > 0 && s < 28123) {
candidates[s] = true;
}
}
}
for(var k in candidates) {
if(!candidates.hasOwnProperty(k)) continue;
// We are interested in the numbers that can't be written as the sum of two abundant numbers.
if(candidates[k] === false) {
sum += parseInt(k);
}
}
console.log(sum);