-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path507_Perfect_Number.js
More file actions
55 lines (48 loc) · 1.31 KB
/
507_Perfect_Number.js
File metadata and controls
55 lines (48 loc) · 1.31 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
53
54
55
/*
507. Perfect Number
We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself.
Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not.
Note: The input number n will not exceed 100,000,000.
*/
const expect = require('expect');
describe('507 Perfect Number', () => {
it('returns true', () => {
//arrange
const input = 28;
const expected = true;
//act
const actual = checkPerfectNumber(input);
//assert
expect(expected).toBe(actual);
});
it('returns true', () => {
//arrange
const input = 496;
const expected = true;
//act
const actual = checkPerfectNumber(input);
//assert
expect(expected).toBe(actual);
});
it('returns true', () => {
//arrange
const input = 33550336;
const expected = true;
//act
const actual = checkPerfectNumber(input);
//assert
expect(expected).toBe(actual);
});
});
const checkPerfectNumber = (num) => {
if (num === 1) return false;
const divisors = [1];
for (let index = 2; index <= Math.sqrt(num); index++) {
if (num % index === 0) {
divisors.push(index);
divisors.push(num / index);
}
}
const sum = divisors.reduce((acc, cur) => acc + cur);
return sum === num;
};