So I want to write a func which get a number and return True if it a "perfect number". I need to do it without using for or while in my function. Here is what I tried to do -
def question_1(num):
i = 1
def checkDivide(n, num):
if num % n == 0:
return n
else:
return 0
def SumThemAll(num, i):
if i == num:
return 0
else:
return i + SumThemAll(num, checkDivide(i + 1, num))
if num == SumThemAll(num, i):
return True
else:
return False
The problem is when I get to an integer which does not divide with the number i want to check but I dont know how to fix it. any idea how to make it more fast will help too
You could do it like this:
def perfect(num: int):
def recursive(num: int, i=1):
if num == i:
return 0
elif num % i == 0:
return i+recursive(num, i+1)
else:
return recursive(num, i+1)
return False if num < 2 else recursive(num)==num
And the non-recursive solution just to check:
def non_recursive(num: int):
return sum(i for i in range(1, num) if num%i==0) == num