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
CodePudding user response:
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 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
CodePudding user response:
Here is a recursive solution. However, it comes with a WARNING.
The largest value that this can process is 1994 before a RecursionError is raised.
def isperfect(n):
def isperfect_(n, m, s=0):
if m == 0:
return n == s
if n % m == 0:
s = m
return isperfect_(n, m - 1, s)
return False if n < 2 else isperfect_(n, n//2)