【问题标题】:Project euler 23, gives 64 higher than it shouldProject euler 23,给出的值比它应该的高 64
【发布时间】:2019-11-07 10:14:25
【问题描述】:

这段代码比它应该的高 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.

【问题讨论】:

  • 非常感谢!问题解决了

标签: javascript math


【解决方案1】:

函数arrayCanSumToX似乎有2个错误:

  • 当high 从length 开始时,abundantNumbers[high] 超出范围。
  • 将low &lt; high 替换为low &lt;= 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;
};

【讨论】:

    猜你喜欢
    • 2014-10-14
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 1970-01-01
    相关资源
    最近更新 更多