Perfect Number

Pattern: Maths basics

easy

Add up a number's divisors in pairs, only up to its square root, and compare the total with the number.

The problem

You are given a whole number num from 1 to 100,000,000. Its proper divisors are the numbers that divide it exactly, other than num itself. Return true if the proper divisors add up to exactly num. For example, 28 is perfect because 1 + 2 + 4 + 7 + 14 = 28, while 12 is not, because 1 + 2 + 3 + 4 + 6 = 16.

The function name checkPerfectNumber matches LeetCode. Use the link above for the exact statement.

Think first

  • List every divisor of 28 by hand. Do you notice they come in pairs that multiply to 28?
  • In each pair, one number is small. How large can the smaller one be?
  • Which divisor must you leave out of the sum?

Hints

    Brute force, and why it fails

    Try every d from 1 to num - 1, add the ones that divide num, and compare. That is correct. For num near 100 million it is 100 million divisions, which takes around a second in a fast language and much longer in Python. On a judge that runs many tests, it is too slow.

    The key insight

    Divisors come in pairs (d, num / d), and the smaller of each pair is at most the square root. Finding the small one gives you the large one for free, so the loop shrinks from num steps to about √num.

    Dry run

    10 
    num28
    sum1

    num = 28. 1 always divides it and is not 28 itself, so sum starts at 1. The array lists the divisors found so far.

    Step 1 of 6

    The plan

    if num <= 1:
        return false
    sum = 1                          # 1 always counts; num itself never does
    d = 2
    while d <= num div d:            # same as d * d <= num, but cannot overflow
        if num mod d == 0:
            sum = sum + d
            if d != num div d:       # skip the second copy for perfect squares
                sum = sum + num div d
        d = d + 1
    return sum == num
    

    Complexity

    Time
    O(√num)
    Space
    O(1)

    The loop runs about √num times, so at most about 10,000 rounds for the largest input. Only a few variables are kept.

    Edge cases

    • num = 1 is not perfect.
    • 6 is the smallest perfect number (1 + 2 + 3). The next are 28, 496, 8128 and 33,550,336.
    • Perfect squares such as 16 must count the root once: 1 + 2 + 8 + 4 = 15, so not perfect.
    • Primes such as 7 have only the divisor 1, so they are never perfect.
    I've built my logic, show the code

    Java

    class Solution {
        public boolean checkPerfectNumber(int num) {
            if (num <= 1) {
                return false;
            }
            int sum = 1;
            for (int d = 2; d <= num / d; d++) {
                if (num % d == 0) {
                    sum += d;
                    if (d != num / d) {
                        sum += num / d;
                    }
                }
            }
            return sum == num;
        }
    }

    C++

    class Solution {
    public:
        bool checkPerfectNumber(int num) {
            if (num <= 1) {
                return false;
            }
            int sum = 1;
            for (int d = 2; d <= num / d; d++) {
                if (num % d == 0) {
                    sum += d;
                    if (d != num / d) {
                        sum += num / d;
                    }
                }
            }
            return sum == num;
        }
    };

    Python

    class Solution:
        def checkPerfectNumber(self, num: int) -> bool:
            if num <= 1:
                return False
            total = 1
            d = 2
            while d <= num // d:
                if num % d == 0:
                    total += d
                    if d != num // d:
                        total += num // d
                d += 1
            return total == num

    Common mistakes

    • Including num itself, by starting at d = 1 and adding the partner num / 1.
    • Adding a perfect square's root twice.
    • Writing the loop as d * d <= num, which can overflow in 32 bits for inputs near the limit. d <= num / d is the same test without that risk.
    • Looping all the way to num, which is too slow for the largest inputs.

    Similar problems