Call a whole number above zero perfect when adding up its proper divisors gives the number back. Its proper divisors are the positive whole numbers that divide it exactly, other than itself.
Given an integer num, return true if it is a perfect number and false if it is not.
Example 1
Input: num = 496 Output: true Why: 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248 = 496
2 more examples and the constraints
Example 2
Input: num = 12 Output: false Why: 1 + 2 + 3 + 4 + 6 = 16, which is more than 12
Example 3
Input: num = 1 Output: false Why: 1 has no proper divisors, so the sum is 0
Constraints
- 1 ≤ num ≤ 100,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Try every candidateO(n)
- Divisor pairs to √nO(√n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for num = 100,000,000 | Verdict |
|---|---|---|---|
| Try every candidate | O(n) | Correct, far too many tests | |
| Divisor pairs to √n | O(√n) | Best; 10,000 tests at most |
n = num.
Edge cases to test
- num = 1. It has no proper divisors, so the answer is false; do not start the total at 1 for it.
- Perfect squares. For 16, the divisor 4 pairs with itself; count it once, giving 1 + 2 + 4 + 8 = 15.
- Primes. A prime like 7 only has the divisor 1, so the sum is 1.
- The largest perfect number in range. 33550336 must come out true.
- Numbers whose sum is too big. 12 sums to 16 and 945 to 975; more than num is still false.
Common mistakes
- Adding num itself as a divisor, which makes every sum too large.
- Adding the square root twice when num is a perfect square.
- Returning true for 1 because the total was started at 1.
How to talk through it
- 1Clarify. Does the number itself count as a divisor? Is 1 perfect?
- 2Give the brute force. Try every d up to num / 2: O(n), 50 million tests at the limit.
- 3Use divisor pairs. Each d below the square root brings its partner num / d with it.
- 4Handle the details. Start at 1, special-case num = 1, and count a square root once.
- 5Test out loud. Try 1, 6, 16 and 12 before you finish.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?