这段代码比它应该的高出64,我知道一些重复的问题,但是这些解决方案都不能解决我的问题。
https://projecteuler.net/problem=23
完全数是指它的适当除数之和与其数完全相等的一个数。例如,28的适当除数之和为1+2+4+7+ 14 = 28,这意味着28是一个完美数。
如果一个数n的适当除数之和小于n,则称为亏,如果这个数大于n,则称它为富足数。
由于12是最小的富足数,1+2+3+4+6= 16,可以写成两个富足数之和的最小数是24。通过数学分析,可以证明所有大于28123的整数都可以写成两个丰富数的和。然而,这个上限不能通过分析进一步降低,即使已知不能表示为两个丰富数之和的最大数小于这个极限。
找出所有正整数的和,这些正整数不能写成两个丰富数的和。
const abundantNumbers = [];
let result = 0;
const isItAbundant = number => {
let divisorsSum = 1;
for (let i = 2; i <= Math.sqrt(number); i++) {
if (number % i === 0) {
divisorsSum += i;
divisorsSum += number / i;
}
}
if (Math.sqrt(number) % 1 === 0) {
divisorsSum -= Math.sqrt(number);
}
return divisorsSum > number ? 1 : 0;
};
const populateAbundantNumbers = () => {
for (let i = 12; i < 28123; i++) {
if (isItAbundant(i)) {
abundantNumbers.push(i);
}
}
};
const arrayCanSumToX = numb => {
const length = abundantNumbers.length;
let low = 0;
let high = length;
while (low < high) {
if (abundantNumbers[low] + abundantNumbers[high] === numb) {
return true;
} else if (abundantNumbers[low] + abundantNumbers[high] < numb) {
low++;
} else {
high--;
}
}
return false;
};
const checkIfProductOfTwoAbundant = () => {
for (let i = 1; i < 28123; i++) {
if (!arrayCanSumToX(i)) {
result += i;
}
}
return result;
};
populateAbundantNumbers();
checkIfProductOfTwoAbundant();
// => 4179935
// Gives 64 higher than correct solution.发布于 2019-11-06 23:37:48
函数arrayCanSumToX中似乎有两个错误:
bounds.
high从length开始时,abundantNumbers[high]离开了high low < high by low <= high,允许获得相同的丰富数字两倍,就像在24 = 12 + 12.的例子中一样
拟议变动:
const arrayCanSumToX = numb => {
const length = abundantNumbers.length;
let low = 0;
let high = length-1;
while (low <= high) {
if (abundantNumbers[low] + abundantNumbers[high] === numb) {
return true;
} else if (abundantNumbers[low] + abundantNumbers[high] < numb) {
low++;
} else {
high--;
}
}
return false;
};https://stackoverflow.com/questions/58731525
复制相似问题