Sam12
Sam12

Reputation: 1805

Sum divisors function in Python

This is an example for a number(45) that the sum_divisors end with 0. For example: 45->33->15->9->4->3->1->0 Some numbers like (6) repeat themselves until no end.. I have to build a function which checks if the number is the first case(returns ture) or not..

The function is_finite returns False for num=4 .any idea why?

def is_finite(num):
    x=0
    while(num!=0 and x!=num):
        x=num
        num=sum_divisors(num)

    if num==0 :
        return True
    else:
        return False

def sum_divisors(n):
    sum=1
    x=int(n**0.5)
    for i in range(2,(x//1)+1):
        if n%i==0:
            sum=sum+i
        if n%i==0 and n/i!=i:
            sum=sum+(n/i)            
    return int(sum)

Upvotes: 0

Views: 6353

Answers (2)

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27201

Start by defining a get_divisors function:

def get_divisors(num):
    return [i for i in range(1, num) if num % i == 0]

Then your sum_divisors function is simply:

def sum_divisors(num):
    return sum(get_divisors(num))

When crafting your is_finite function, you will need to cache your previous results and check if a number is repeated.

def is_finite(num):
    previous = []

    while num != 0:
        if num in previous:
            return False

        previous.append(num)
        num = sum_divisors(num)

    return True

If you don't do this, you'll get an infinite loop.

Upvotes: 3

happydave
happydave

Reputation: 7187

To return true, sum_divisors would have to return 0. But the sum variable starts at 1 and only adds positive numbers, so the function will never return 0.

Upvotes: 3

Related Questions