We can check if a number is a perfect number in Python easily with a simple function. A number is perfect is the divisors of a number (excluding the number itself) sum to the number.
def checkPerfectNumber(n):
sum_div = 0
for i in range(1, n // 2 + 1):
if (n % i == 0):
sum_div = sum_div + i
if (sum_div == n):
return True
else:
return False
print(checkPerfectNumber(6))
print(checkPerfectNumber(13))
print(checkPerfectNumber(28))
#Output:
True
False
True
There are many interesting definitions of different kinds of numbers in mathematics. One such type of number which has been studied throughout history is the perfect number.
A perfect number is a positive integer which is equal to the sum of its factors, excluding the number itself.
With Python, we can easily define a function which will check to see if a number is a perfect number.
To check if a number is a perfect number, we just need to loop over the numbers between 1 and the number divided by 2 (because no integer divisor can be greater than the number divided by 2).
Then, at each step, we will check if the number is divisible by the loop iteration number and if it is, we will add it to a running total of the sum of the other divisors.
After the loop has completed, we will check if the sum of the divisors equals the number.
Below is a function which will check if a number is a perfect number in Python.
def checkPerfectNumber(n):
sum_div = 0
for i in range(1, n // 2 + 1):
if (n % i == 0):
sum_div = sum_div + i
if (sum_div == n):
return True
else:
return False
print(checkPerfectNumber(6))
print(checkPerfectNumber(13))
print(checkPerfectNumber(28))
#Output:
True
False
True
Hopefully this article has been useful for you to learn about perfect numbers and how you can check if a number is a perfect number in Python.