feat(euler): 21 - amicable numbers

This commit is contained in:
newt 2024-10-09 18:02:44 +01:00
parent 4a2ab74708
commit 8c5377ca8c
2 changed files with 37 additions and 1 deletions

View file

@ -32,7 +32,7 @@ The source code can be found in the [src](src) directory. My thoughts about some
- [x] [18 - Maximum path sum I](src/18%20-%20Maximum%20path%20sum%20I.ts) - [x] [18 - Maximum path sum I](src/18%20-%20Maximum%20path%20sum%20I.ts)
- [x] [19 - Counting Sundays](src/19%20-%20Counting%20Sundays.ts) - [x] [19 - Counting Sundays](src/19%20-%20Counting%20Sundays.ts)
- [x] [20 - Factorial digit sum](src/20%20-%20Factorial%20digit%20sum.ts) - [x] [20 - Factorial digit sum](src/20%20-%20Factorial%20digit%20sum.ts)
- [ ] 21 - Amicable numbers - [x] [21 - Amicable numbers](src/21%20-%20Amicable%20numbers.ts)
- [ ] 22 - Names scores - [ ] 22 - Names scores
- [ ] 23 - Non-abundant sums - [ ] 23 - Non-abundant sums
- [ ] 24 - Lexicographic permutations - [ ] 24 - Lexicographic permutations

View file

@ -0,0 +1,36 @@
// Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
// 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.
// 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.
// Evaluate the sum of all the amicable numbers under 10000.
export = {};
const findProperDivisors = (number: number) => {
const divisors: number[] = [1];
for (let i = 2; i < number; i++) {
if (number % i === 0) {
divisors.push(i);
}
}
return divisors;
};
const d = (n: number) => findProperDivisors(n).reduce((a, b) => a + b);
const findAmicableNumbers = (upperBound: number) => {
const amicableNumbers: number[] = [];
for (let a = 0; a < upperBound; a++) {
const b = d(a);
if (d(b) === a && a !== b) {
amicableNumbers.push(a);
}
}
return amicableNumbers;
};
// Output
console.log(findAmicableNumbers(10000).reduce((a, b) => a + b));