2018-09-30 22:01:58 +00:00
---
id: 5900f3811000cf542c50fe94
title: 'Problem 21: Amicable numbers'
2020-11-27 18:02:05 +00:00
challengeType: 5
2019-08-05 16:17:33 +00:00
forumTopicId: 301851
2021-01-13 02:31:00 +00:00
dashedName: problem-21-amicable-numbers
2018-09-30 22:01:58 +00:00
---
2020-11-27 18:02:05 +00:00
# --description--
2020-02-28 12:39:47 +00:00
2020-11-27 18:02:05 +00:00
Let d(`n`) be defined as the sum of proper divisors of `n` (numbers less than `n` which divide evenly into `n` ).
2020-02-28 12:39:47 +00:00
2020-11-27 18:02:05 +00:00
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.
2020-02-28 12:39:47 +00:00
2018-09-30 22:01:58 +00:00
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
2020-02-28 12:39:47 +00:00
Evaluate the sum of all the amicable numbers under `n` .
2020-11-27 18:02:05 +00:00
# --hints--
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
`sumAmicableNum(1000)` should return a number.
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
```js
assert(typeof sumAmicableNum(1000) === 'number');
```
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
`sumAmicableNum(1000)` should return 504.
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
```js
assert.strictEqual(sumAmicableNum(1000), 504);
2018-09-30 22:01:58 +00:00
```
2020-11-27 18:02:05 +00:00
`sumAmicableNum(2000)` should return 2898.
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
```js
assert.strictEqual(sumAmicableNum(2000), 2898);
```
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
`sumAmicableNum(5000)` should return 8442.
2018-09-30 22:01:58 +00:00
```js
2020-11-27 18:02:05 +00:00
assert.strictEqual(sumAmicableNum(5000), 8442);
```
2020-09-15 16:57:40 +00:00
2020-11-27 18:02:05 +00:00
`sumAmicableNum(10000)` should return 31626.
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
```js
assert.strictEqual(sumAmicableNum(10000), 31626);
2018-09-30 22:01:58 +00:00
```
2020-11-27 18:02:05 +00:00
# --seed--
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
## --seed-contents--
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
```js
function sumAmicableNum(n) {
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
return n;
}
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
sumAmicableNum(10000);
```
2018-09-30 22:01:58 +00:00
2020-11-27 18:02:05 +00:00
# --solutions--
2018-09-30 22:01:58 +00:00
```js
const sumAmicableNum = (n) => {
const fsum = (n) => {
let sum = 1;
for (let i = 2; i < = Math.floor(Math.sqrt(n)); i++)
if (Math.floor(n % i) === 0)
sum += i + Math.floor(n / i);
return sum;
};
let d = [];
let amicableSum = 0;
for (let i=2; i< n ; i + + ) d [ i ] = fsum ( i ) ;
for (let i=2; i< n ; i + + ) {
let dsum = d[i];
if (d[dsum]===i & & i!==dsum) amicableSum += i+dsum;
}
return amicableSum/2;
};
```