-
Notifications
You must be signed in to change notification settings - Fork 294
Expand file tree
/
Copy pathisPerfectNumber.js
More file actions
52 lines (37 loc) · 1.33 KB
/
isPerfectNumber.js
File metadata and controls
52 lines (37 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
Write a function `isPerfectNumber` which takes an integer `num` as input and returns a boolean indicating whether the number is a perfect number.
What is a perfect number?
- A perfect number is a positive integer that is equal to the sum of its proper divisors, excluding the number itself.
Example:
- Input: 6
- Output: true
- Explanation: The divisors of 6 are 1, 2, and 3. 1 + 2 + 3 = 6, so 6 is a perfect number.
- Input: 28
- Output: true
- Explanation: The divisors of 28 are 1, 2, 4, 7, and 14. 1 + 2 + 4 + 7 + 14 = 28, so 28 is a perfect number.
- Input: 10
- Output: false
- Explanation: The divisors of 10 are 1, 2, and 5. 1 + 2 + 5 = 8, which is not equal to 10, so 10 is not a perfect number.
- Input: 1
- Output: false
- Explanation: The divisors of 1 are none (it doesn't have proper divisors), so 1 is not a perfect number.
Once you've implemented the logic, test your code by running
- `npm run test-perfect`
*/
function isPerfectNumber(num) {
if (num <= 1) return false;
let summ = 0;
for (let i = 1; i * i <= num; i++) {
if (num % i === 0) {
if (i !== num) {
summ += i;
}
let other = num / i;
if (other !== i && other !== num) {
summ += other;
}
}
}
return summ === num;
}
module.exports = { isPerfectNumber };