|
1 | 1 | /** |
2 | | - * Author: dephraiim |
3 | | - * License: GPL-3.0 or later |
4 | | - * |
5 | | - * == Perfect Number == |
6 | | - * In number theory, a perfect number is a positive integer that is equal to the sum of |
7 | | - * its positive divisors(factors), excluding the number itself. |
8 | | - * For example: 6 ==> divisors[1, 2, 3, 6] |
9 | | - * Excluding 6, the sum(divisors) is 1 + 2 + 3 = 6 |
10 | | - * So, 6 is a Perfect Number |
11 | | - * Other examples of Perfect Numbers: 28, 486, ... |
12 | | - * |
13 | | - * More on Perfect Number: |
14 | | - * https://en.wikipedia.org/wiki/Perfect_number |
15 | | - * |
| 2 | + * @function isPerfectNumber |
| 3 | + * @description A perfect number is a positive integer that is equal to the sum |
| 4 | + * of its positive divisors, excluding the number itself. For example, 28 is |
| 5 | + * perfect because 1 + 2 + 4 + 7 + 14 = 28. |
| 6 | + * @param {number} n - A positive integer |
| 7 | + * @returns {boolean} - True if n is a perfect number, false otherwise |
| 8 | + * @see https://en.wikipedia.org/wiki/Perfect_number |
| 9 | + * @example isPerfectNumber(6) => true |
| 10 | + * @example isPerfectNumber(28) => true |
| 11 | + * @example isPerfectNumber(12) => false |
16 | 12 | */ |
17 | | - |
18 | | -const factorsExcludingNumber = (n) => { |
19 | | - return [...Array(n).keys()].filter((num) => n % num === 0) |
20 | | -} |
21 | | - |
22 | | -const perfectNumber = (n) => { |
23 | | - const factorSum = factorsExcludingNumber(n).reduce((num, initialValue) => { |
24 | | - return num + initialValue |
25 | | - }, 0) |
26 | | - |
27 | | - return factorSum === n |
| 13 | +const isPerfectNumber = (n) => { |
| 14 | + if (!Number.isInteger(n) || n < 1) { |
| 15 | + throw new TypeError('Input must be a positive integer') |
| 16 | + } |
| 17 | + if (n === 1) return false |
| 18 | + let sum = 1 |
| 19 | + for (let i = 2; i <= Math.sqrt(n); i++) { |
| 20 | + if (n % i === 0) { |
| 21 | + sum += i |
| 22 | + if (i !== n / i) sum += n / i |
| 23 | + } |
| 24 | + } |
| 25 | + return sum === n |
28 | 26 | } |
29 | 27 |
|
30 | | -export { perfectNumber } |
| 28 | +export { isPerfectNumber } |
0 commit comments