Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find if a number is perfect number with a recursive code

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could do it like this:

def perfect(num: int):
    def recursive(num: int, i=1):
        total = 0
        if num == i:
            return total
        elif num % i == 0:
            total += i
            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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading