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:
num = 28
True
Explanation: 28 = 1 + 2 + 4 + 7 + 14
num = 6
True
Explanation: 6 = 1 + 2 + 3
num = 496
True
Explanation: 496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248
num = 12
False
num
?
num
guaranteed to be positive?
num = 1
?
num = 1
, it should return False
since by definition it doesn’t meet the sum condition.Initial Check: If num
is 1 or less, immediately return False
since 1 has no positive divisors other than itself.
num
excluding num
itself.num
to improve efficiency (d
and num/d
will both be divisors).num
.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
O(sqrt(n))
num
, making it efficient for large values.O(1)
This approach ensures the problem is solved efficiently within the constraints provided.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?