freeCodeCamp/curriculum/challenges/chinese/10-coding-interview-prep/project-euler/problem-23-non-abundant-sum...

90 lines
2.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

---
id: 5900f3831000cf542c50fe96
title: 问题23非丰富的总和
challengeType: 5
videoUrl: ''
dashedName: problem-23-non-abundant-sums
---
# --description--
完美数字是一个数字其正确除数的总和恰好等于数字。例如28的适当除数之和为1 + 2 + 4 + 7 + 14 = 28这意味着28是一个完美数。如果`n`的适当除数之和小于`n` ,则`n`被称为不足,如果该和超过`n`则称为`n` 。由于12是最小的有限数1 + 2 + 3 + 4 + 6 = 16可以写成两个有限数之和的最小数是24.通过数学分析可以看出所有整数都大于28123可以写成两个数字的总和。然而即使已知不能表示为两个充裕数的总和的最大数小于该限制也不能通过分析进一步减小该上限。找出所有正整数<= `n`的总和,它不能写成两个丰富数字的总和。
# --hints--
`sumOfNonAbundantNumbers(10000)`应返回3731004。
```js
assert(sumOfNonAbundantNumbers(10000) === 3731004);
```
`sumOfNonAbundantNumbers(15000)`应该返回4039939。
```js
assert(sumOfNonAbundantNumbers(15000) === 4039939);
```
`sumOfNonAbundantNumbers(20000)`应返回4159710。
```js
assert(sumOfNonAbundantNumbers(20000) === 4159710);
```
`sumOfNonAbundantNumbers(28123)`应该返回4179871。
```js
assert(sumOfNonAbundantNumbers(28123) === 4179871);
```
# --seed--
## --seed-contents--
```js
function sumOfNonAbundantNumbers(n) {
return n;
}
sumOfNonAbundantNumbers(28123);
```
# --solutions--
```js
function abundantCheck(number) {
let sum = 1;
for (let i = 2; i <= Math.sqrt(number); i += 1) {
if(number % i === 0) {
sum += i + +(i !== Math.sqrt(number) && number / i);
}
}
return sum > number;
}
function sumOfNonAbundantNumbers(n) {
let sum = 0;
const memo = {};
let abundantList = [];
// Function checkSum checks if num can be represented as a sum of numbers in the stack (array)
const checkSum = (num, stack, memo) => {
for (let i = 0; i < stack.length; i += 1) {
if ((num - stack[i]) in memo) return true;
}
return false;
};
for (let i = 1; i <= n; i += 1) {
if (abundantCheck(i)) {
abundantList.push(i);
memo[i] = 1;
}
if (checkSum(i, abundantList, memo)) continue;
sum += i;
}
return sum;
}
```