Skip to content

Commit 762c022

Browse files
authored
algorithm: aliquot sum (#60)
1 parent 519175c commit 762c022

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

Maths/AliquotSum.ts

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @function AliquotSum
3+
* @description Returns the aliquot sum of the provided number
4+
* @summary The aliquot sum of a number n is the sum of all the proper divisors
5+
* of n apart from n itself.
6+
* So, for example, the number 6 has three proper divisors, 1, 2, 3
7+
* Hence its aliquot sum is 1 + 2 + 3 = 6
8+
* For all prime numbers, the aliquot sum is 1, and for 1, the aliquot sum is 0
9+
* @param {number} num The input number
10+
* @return {number} The aliquot sum of the number
11+
* @see [Wikipedia](https://en.wikipedia.org/wiki/Aliquot_sum)
12+
* @example AliquotSum(18) = 21
13+
* @example AliquotSum(15) = 9
14+
*/
15+
export const AliquotSum = (num: number): number => {
16+
if (typeof num !== 'number') throw new TypeError('Input needs to be a number')
17+
if (num < 0) throw new TypeError('Input cannot be negative')
18+
if (!Number.isInteger(num)) throw new TypeError('Input cannot be a decimal')
19+
20+
let sum = 0
21+
22+
for (let i = 1; i <= num / 2; i++) {
23+
if (num % i === 0) sum += i;
24+
}
25+
26+
return sum
27+
}

Maths/test/AliquotSum.test.ts

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import { AliquotSum } from "../AliquotSum";
2+
3+
test.each([[15, 9], [18, 21], [28, 28], [100, 117], [169, 14], [1729, 511], [15625, 3906]])("Aliquot Sum of %i is %i", (num, expected) => {
4+
expect(AliquotSum(num)).toBe(expected)
5+
})

0 commit comments

Comments
 (0)