#507

Perfect Number

Easy
MathMath (Divisor Pairing)Looping to Square Root
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(sqrt(n))
Space
O(1)
O(1)
💡

Intuition

Time O(sqrt(n))Space O(1)

Instead of checking all numbers up to 'n', we can check only up to the square root of 'n'. This is because divisors come in pairs, and if 'i' is a divisor, then 'n/i' is also a divisor.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a variable 'sum' to 1 (since 1 is a divisor for all numbers).
  2. 2Step 2: Loop through all integers 'i' from 2 to the square root of 'n'.
  3. 3Step 3: If 'n' is divisible by 'i', add 'i' and 'n/i' to 'sum' (avoid adding 'n' itself).
  4. 4Step 4: After the loop, check if 'sum' equals 'n'.
  5. 5Step 5: Return true if they are equal, otherwise return false.
solution.py9 lines
1def checkPerfectNumber(num):
2    if num <= 1: return False
3    sum = 1
4    for i in range(2, int(num**0.5) + 1):
5        if num % i == 0:
6            sum += i
7            if i != num // i:
8                sum += num // i
9    return sum == num

Complexity note: The time complexity is O(sqrt(n)) because we only loop up to the square root of 'n', significantly reducing the number of iterations. The space complexity is O(1) as we use a constant amount of extra space.

  • 1Divisors can be found in pairs, which allows us to reduce the number of checks needed.
  • 2The sum of divisors excluding the number itself is the key to identifying perfect numbers.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.