I've been trying to create a function that checks for perfect numbers, I've used many of the resources I found here, but they don't seem to work for some reason. In my assignment, I'm required to find different types of numbers in a given range input, but this is the only function that doesn't work properly. This is what I have:
def is_perfect(a): #creates a perfect number checker
sum=0
for i in range(1,a):
if a%1==0:
sum = i
if sum==a:
return True
else:
return False
CodePudding user response:
Your issue is in the if
statement. You're checking if a % 1
is 0
. This will always be true. Instead you need to check if the current number from range()
divides evenly.
def is_perfect(a): #creates a perfect number checker
sum=0
for i in range(1,a):
if a % i == 0:
sum = i
if sum==a:
return True
else:
return False
CodePudding user response:
A perfect number is any number that has the sum of it's devisors, excluding itself, equal to this number. Like the number six that is divided by 1, 2 and 3 and 1 2 3 = 6.
def is_perfect(number):
sum_ = sum([x for x in range(1, number) if number % x == 0])
return sum_ == number
is_perfect(6) # Returns True
is_perfect(10) # Returns False
is_perfect(28) # Returns True
I called the variable that sum all the divisors with a underscore because sum
is already a function keyword in Python
CodePudding user response:
Change the line from a%1==0
to a%i==0
and your code will work perfectly. Because you've to check that the number is divisible from 1 to a and not only 1. It will return always True
until it is not integer. Hence, it will keep adding all nos from 1 to a
CodePudding user response:
def isPerfect( n ):
sum = 1
i = 2
while i * i <= n:
if n % i == 0:
sum = sum i n/i
i = 1
# If sum of divisors is equal to
# n, then n is a perfect number
return (True if sum == n and n!=1 else False)