↓Skip to main content
  1. LeetCode/

LeetCode 507: Perfect Number

·1 min· ·
LeetCode Easy Math
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-25

  • Submissions: Accepted (first try)

Approach
#

Divisors d and n / d come in pairs, so enumerate d from 2 to √n (as in Number Theory Template 2): add d when it divides, and n / d too when they differ. 1 always divides but n itself does not count, so start the sum at 1 and rule out n = 1.

My Solution
#

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

Complexity
#

Time O(√n), space O(1).

Mistakes to Avoid
#

  • Do not count n itself.
  • For a perfect square add √n once.
  • The proper divisor sum of n = 1 is 0.

Interview Explanation
#

Divisors pair up, so I enumerate to √n, adding d and n / d for each divisor (the square root once), starting from 1 and excluding n itself, then compare with n. Time O(√n).

Related

LeetCode 263: Ugly Number
·1 min
LeetCode Easy Math
LeetCode 263 note: only positive numbers can be ugly; divide out every factor 2, 3 and 5 and check whether 1 remains
LeetCode 292: Nim Game
·1 min
LeetCode Easy Math Brainteaser Minimax-Algorithm Game-Theory
LeetCode 292 note: whoever faces a multiple of 4 stones loses, so the first player wins when n % 4 != 0
LeetCode 326: Power of Three
·1 min
LeetCode Easy Math Recursion
LeetCode 326 note: divide by 3 while possible and check for 1; without loops, n is a power of three exactly when it divides 3^19
LeetCode 504: Base 7
·1 min
LeetCode Easy Math String
LeetCode 504 note: repeatedly take % 7 and // 7 of the absolute value, then add the sign and reverse; handle 0 separately
LeetCode 509: Fibonacci Number
·1 min
LeetCode Easy Math Dynamic-Programming Recursion Memoization
LeetCode 509 note: the starting point of 1D DP; only the previous two terms are needed, so roll two variables
LeetCode 415: Add Strings
·2 mins
LeetCode Easy Math String Simulation
LeetCode 415 note: add digit by digit from the ends with two pointers, tracking the carry, and append any leftover carry after the loop