algoadvance

A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. Given an integer num, write a function that returns True if num is a perfect number, otherwise, return False.

Example:

Clarifying Questions

  1. What is the range of num?
    • The problem does not specify a range, so we assume any positive integer within the limits of typical integer operations in Python.
  2. Is num guaranteed to be positive?
    • The problem specifies the number is a positive integer.
  3. What should we return for the smallest input like num = 1?
    • For num = 1, it should return False since by definition it doesn’t meet the sum condition.

Strategy

  1. Initial Check: If num is 1 or less, immediately return False since 1 has no positive divisors other than itself.

  2. Divisor Calculation:
    • Find all divisors of num excluding num itself.
    • Only iterate up to the square root of num to improve efficiency (d and num/d will both be divisors).
  3. Sum and Compare:
    • Sum up all unique divisors found in step 2.
    • Check if the sum equals num.

Code

def checkPerfectNumber(num):
    if num <= 1:
        return False

    divisors_sum = 1
    sqrt_num = int(num**0.5)

    for i in range(2, sqrt_num + 1):
        if num % i == 0:
            divisors_sum += i
            if i != num // i:
                divisors_sum += num // i
    
    return divisors_sum == num

Time Complexity

This approach ensures the problem is solved efficiently within the constraints provided.

Try our interview co-pilot at AlgoAdvance.com