Perfect Number - Problem

A perfect number is a fascinating mathematical concept - it's a positive integer that equals the sum of all its positive divisors, excluding the number itself. Think of it as a number that is perfectly balanced with its factors!

For example, 6 is perfect because its divisors are 1, 2, and 3, and 1 + 2 + 3 = 6. Similarly, 28 is perfect because 1 + 2 + 4 + 7 + 14 = 28.

Your task: Given an integer n, determine if it's a perfect number. Return true if it is, false otherwise.

Note: A divisor of an integer x is any integer that divides x evenly (with no remainder).

Input & Output

example_1.py โ€” Basic Perfect Number
$ Input: 6
โ€บ Output: true
๐Ÿ’ก Note: 6 is a perfect number because its proper divisors are 1, 2, and 3, and 1 + 2 + 3 = 6.
example_2.py โ€” Larger Perfect Number
$ Input: 28
โ€บ Output: true
๐Ÿ’ก Note: 28 is a perfect number because its proper divisors are 1, 2, 4, 7, and 14, and 1 + 2 + 4 + 7 + 14 = 28.
example_3.py โ€” Not Perfect Number
$ Input: 12
โ€บ Output: false
๐Ÿ’ก Note: 12 is not perfect because its proper divisors are 1, 2, 3, 4, and 6, and 1 + 2 + 3 + 4 + 6 = 16 โ‰  12.

Constraints

  • 1 โ‰ค num โ‰ค 108
  • Note: Perfect numbers are extremely rare
  • The first few perfect numbers are: 6, 28, 496, 8128...

Visualization

Tap to expand
Perfect Number: Divisor Pair Visualization (n=28)12828 รท 1 = 28 (but we exclude 28)21428 รท 2 = 144728 รท 4 = 7Result: 1 + 2 + 4 + 7 + 14 = 28 โœ“We only checked up to โˆš28 โ‰ˆ 5.3, finding all divisors efficiently!
Understanding the Visualization
1
Identify the Pattern
Perfect numbers equal the sum of their proper divisors
2
Find Divisor Pairs
Every divisor i has a pair n/i (except when i = โˆšn)
3
Optimize Search
Only check numbers up to โˆšn to find all divisors
4
Sum and Compare
Add all divisors and check if sum equals the original number
Key Takeaway
๐ŸŽฏ Key Insight: By recognizing that divisors come in pairs, we can reduce our search space from O(n) to O(โˆšn), making the algorithm efficient enough to handle large numbers while maintaining correctness.
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen