Skip to content

Commit 53b1f66

Browse files
authored
Project Euler 021 (TheAlgorithms#1347)
* feat: Project Euler Problem 21 * test: Project Euler 21 * fix: test description in Project Euler 21
1 parent ecac786 commit 53b1f66

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

Project-Euler/Problem021.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { aliquotSum } from '../Maths/AliquotSum.js'
2+
3+
/**
4+
* Problem 21 - Amicable numbers
5+
*
6+
* @see {@link https://projecteuler.net/problem=21}
7+
*
8+
* Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
9+
* 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.
10+
* For example, the proper divisors of 220 are 1,2,4,5,10,11,20,22,44,55 and 110; therefore d(220) = 284.
11+
* The proper divisors of 284 are 1,2,4,71 and 142; so d(284) = 220.
12+
* Evaluate the sum of all amicable numbers under 10000
13+
*
14+
* @author PraneethJain
15+
*/
16+
17+
function problem21 (n) {
18+
if (n < 2) {
19+
throw new Error('Invalid Input')
20+
}
21+
22+
let result = 0
23+
for (let a = 2; a < n; ++a) {
24+
const b = aliquotSum(a) // Sum of all proper divisors of a
25+
// Check if b > a to ensure each pair isn't counted twice, and check if sum of proper divisors of b is equal to a
26+
if (b > a && aliquotSum(b) === a) {
27+
result += a + b
28+
}
29+
}
30+
return result
31+
}
32+
33+
export { problem21 }

Project-Euler/test/Problem021.test.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { problem21 } from '../Problem021.js'
2+
3+
describe('check sum of amicable numbers under n', () => {
4+
test('should be invalid input if number is negative', () => {
5+
expect(() => problem21(-1)).toThrowError('Invalid Input')
6+
})
7+
test('should be invalid input if number is 0', () => {
8+
expect(() => problem21(0)).toThrowError('Invalid Input')
9+
})
10+
// Project Euler Condition Check
11+
test('if the number is greater or equal to 1', () => {
12+
expect(problem21(10000)).toBe(31626)
13+
})
14+
})

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy