Skip to content

algorithm: aliquot sum #60

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Oct 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions Maths/AliquotSum.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* @function AliquotSum
* @description Returns the aliquot sum of the provided number
* @summary The aliquot sum of a number n is the sum of all the proper divisors
* of n apart from n itself.
* So, for example, the number 6 has three proper divisors, 1, 2, 3
* Hence its aliquot sum is 1 + 2 + 3 = 6
* For all prime numbers, the aliquot sum is 1, and for 1, the aliquot sum is 0
* @param {number} num The input number
* @return {number} The aliquot sum of the number
* @see [Wikipedia](https://en.wikipedia.org/wiki/Aliquot_sum)
* @example AliquotSum(18) = 21
* @example AliquotSum(15) = 9
*/
export const AliquotSum = (num: number): number => {
if (typeof num !== 'number') throw new TypeError('Input needs to be a number')
if (num < 0) throw new TypeError('Input cannot be negative')
if (!Number.isInteger(num)) throw new TypeError('Input cannot be a decimal')

let sum = 0

for (let i = 1; i <= num / 2; i++) {
if (num % i === 0) sum += i;
}

return sum
}
5 changes: 5 additions & 0 deletions Maths/test/AliquotSum.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { AliquotSum } from "../AliquotSum";

test.each([[15, 9], [18, 21], [28, 28], [100, 117], [169, 14], [1729, 511], [15625, 3906]])("Aliquot Sum of %i is %i", (num, expected) => {
expect(AliquotSum(num)).toBe(expected)
})