GeezerVison is showing github.com — Project Euler 021 (#1347) · Algorithms-Learn/JavaScript@53b1f66
File tree
Expand file treeCollapse file tree
Open diff view settings
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboard +33Lines changed: 33 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
|
| 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 } |
Collapse file
Copy file name to clipboard +14Lines changed: 14 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
|
| 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 | +}) |