A perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself.
Example: The first perfect number is 6, because 1, 2, and 3 are its proper positive divisors, and 1 + 2 + 3 = 6. The next perfect number is 28 = 1 + 2 + 4 + 7 + 14, and so on.
Output 1 if the number is a perfect number else output 0.
Input 1: 6
Output 1: 1
Input 2: 10
Output 2: 0
Perfect number in Python
# Read the input
n = int(input())
ans = 0
for i in range(1, n//2 + 1):
if(n%i == 0):
ans += i
print(int(ans==n))
# Alternate, more efficient solution
# Notice that all the factors exist in pairs. For example 36 has the factors
# (1, 36), (2, 18), (3, 12), (4, 9) and (6, 6). However in this case, i.e. the
# case of perfect squares, you need to be careful as the final pair has 6 twice
# and you only need one of them.
ans = 0
# Now, you can simply run the for loop from 1 to floor(sqroot(n))
for i in range(1, int(n**0.5)+1):
# Check if n is divisible by i; if yes, then add 'i' and 'n/i' to the final ans
# But make sure that i and n/i are not equal. If they're equal just add one of
# them
if(n%i == 0):
temp = (lambda i: i + n/i if i != n/i else i)
ans += temp(i)
# Check if n*2 is equal to ans. This is done because the code above will also add
# the number itself.
print(int(n*2==ans))
Comments