0

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

arbel
  • 5
  • 3

2 Answers2

0

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
Nin17
  • 2,821
  • 2
  • 4
  • 14
0

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)
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
  • Doesn't that depend on your recursion limit? With a recursion limit of 3000, the maximum value that doesn't give me a RecursionError is 5941. – Nin17 May 04 '22 at 14:19