Tutorialspoint
Problem
Solution
Submissions

Perfect Number Check

Certification: Basic Level Accuracy: 75% Submissions: 4 Points: 10

Write a C++ program to determine if a given number equals the sum of its proper divisors (excluding itself).

Example 1
  • Input: num = 6
  • Output: true
  • Explanation:
    • Step 1: Find all proper divisors of 6 (numbers that divide 6 evenly, excluding itself): 1, 2, 3.
    • Step 2: Calculate the sum of these divisors: 1 + 2 + 3 = 6.
    • Step 3: Compare the sum with the original number: 6 = 6.
    • Step 4: Since they are equal, return true.
Example 2
  • Input: num = 28
  • Output: true
  • Explanation:
    • Step 1: Find all proper divisors of 28 (numbers that divide 28 evenly, excluding itself): 1, 2, 4, 7, 14.
    • Step 2: Calculate the sum of these divisors: 1 + 2 + 4 + 7 + 14 = 28.
    • Step 3: Compare the sum with the original number: 28 = 28.
    • Step 4: Since they are equal, return true.
Constraints
  • 1 ≤ n ≤ 10^6
  • Note: Numbers equal to the sum of their proper divisors are called perfect numbers
  • Time Complexity: O(sqrt(n))
  • Space Complexity: O(1)
NumberControl StructuresAccentureAirbnb
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Iterate up to sqrt(n) to find divisors
  • Sum divisors and compare with original number
  • Handle n = 1 as a special case

Steps to solve by this approach:

 Step 1: Handle edge cases (numbers less than or equal to 1 are not perfect).

 Step 2: Initialize sum to 1 (since 1 is always a divisor).
 Step 3: Iterate from 2 to the square root of n to find divisors efficiently.
 Step 4: When a divisor is found, add both the divisor and its pair to the sum.
 Step 5: Ensure we don't add a divisor twice if it's a perfect square.
 Step 6: Compare the sum with the original number.
 Step 7: Return true if the sum equals the original number, false otherwise.

Submitted Code :