Perfect Number - Problem

A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself.

A divisor of an integer x is an integer that can divide x evenly (with no remainder).

Given an integer n, return true if n is a perfect number, otherwise return false.

Input & Output

Example 1 — First Perfect Number
$ Input: n = 6
Output: true
💡 Note: The divisors of 6 are 1, 2, and 3. Sum: 1 + 2 + 3 = 6, which equals the number itself.
Example 2 — Second Perfect Number
$ Input: n = 28
Output: true
💡 Note: The divisors of 28 are 1, 2, 4, 7, and 14. Sum: 1 + 2 + 4 + 7 + 14 = 28.
Example 3 — Not Perfect
$ Input: n = 12
Output: false
💡 Note: The divisors of 12 are 1, 2, 3, 4, and 6. Sum: 1 + 2 + 3 + 4 + 6 = 16, which is not equal to 12.

Constraints

  • 1 ≤ n ≤ 108

Visualization

Tap to expand
Perfect Number - Square Root Optimization INPUT n = 6 positive integer Find Divisors of 6 1 2 3 6 (excluded) sqrt(6) = 2.45 Only check up to sqrt(n) Check: i = 2 to 2 (floor of sqrt(6)) ALGORITHM STEPS 1 Initialize sum = 1 1 is always a divisor 2 Loop i = 2 to sqrt(n) Check if i divides n 3 Add pair divisors If n%i==0: add i and n/i 4 Compare sum == n Return true if equal Calculation for n=6: i=2: 6%2==0 sum += 2 + (6/2) = 2 + 3 sum = 1 + 2 + 3 = 6 6 == 6 : true FINAL RESULT true 6 is a Perfect Number! Divisor Sum Breakdown 1 + 2 + 3 = 6 Sum equals n : OK Output: true Key Insight: Square Root Optimization Instead of checking all divisors from 1 to n-1 (O(n)), we only check up to sqrt(n). If i divides n, then both i and n/i are divisors. This reduces time complexity to O(sqrt(n)). Example: For n=6, sqrt(6)=2.45, so we only check i=2. Finding 6%2==0 gives us both 2 and 3. TutorialsPoint - Perfect Number | Square Root Optimization Approach
Asked in
Google 15 Microsoft 12 Amazon 8
32.0K Views
Medium Frequency
~15 min Avg. Time
890 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