# The Balanced Sum

> Some numbers have a rare quality that mathematicians revere.

Canonical URL: <https://datadriven.io/problems/the_balanced_sum>

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Given a positive integer n, return True if n equals the sum of its proper divisors (all divisors excluding n). Example: 28 = 1+2+4+7+14.

## Worked solution and explanation

### Why this problem exists in real interviews

Checking if a number is perfect tests **divisor enumeration** and whether you optimize by only checking up to the square root. It is a number theory warm-up.

---

### Break down the requirements

#### Step 1: Find all proper divisors

A proper divisor of n is any positive integer less than n that divides n evenly.

#### Step 2: Sum them and compare to n

If the sum equals n, it is a perfect number.

#### Step 3: Optimize by checking up to sqrt(n)

For each divisor d found below sqrt(n), also include n/d as a divisor.

---

### The solution

**Divisor enumeration up to square root**

```python
def is_perfect(n):
    if n <= 1:
        return False
    divisor_sum = 1
    i = 2
    while i * i <= n:
        if n % i == 0:
            divisor_sum += i
            if i != n // i:
                divisor_sum += n // i
        i += 1
    return divisor_sum == n
```

> **Time and Space Complexity**
>
> **Time:** O(sqrt(n)) since we only check divisors up to the square root.
> 
> **Space:** O(1). A single accumulator.

> **Interviewers Watch For**
>
> The sqrt optimization. Checking all numbers from 1 to n-1 is O(n), which is unnecessary. Also, correctly starting the sum at 1 (since 1 is always a proper divisor).

> **Common Pitfall**
>
> Including n itself in the divisor sum. Proper divisors exclude the number itself. Also, not handling the case where `i == n // i` to avoid double-counting the square root.

---

## Common follow-up questions

- What are the first few perfect numbers? _(Tests knowledge: 6, 28, 496, 8128. They are rare and all known ones are even.)_
- What is the relationship to Mersenne primes? _(Tests number theory: every even perfect number has the form 2^(p-1) * (2^p - 1) where 2^p - 1 is a Mersenne prime.)_
- How would you check if a number is abundant or deficient? _(Tests comparing the divisor sum to n: greater means abundant, less means deficient.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_balanced_sum)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.