-1
def sum_divisors(n):
  sum = 0
  # Return the sum of all divisors of n, not including n
  return sum

print(sum_divisors(0))
# 0
print(sum_divisors(3)) # Should sum of 1
# 1
print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18
# 55
print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51
# 114

I attempted to find the range of the numbers with this that I found on another question asked on here but I'm honestly just completely stumped with this question that I'm being asked even with the help that's alread given within the question.

 for i in xrange(1,n/2+1):
        if n%i == 0:

I'm not sure how to properly input it so it ended up looking like this

def sum_divisors(n):
    for i in xrange(1,n/2+1):
        if n%i == 0:
            sum = 0
        return sum
  # Return the sum of all divisors of n, not including n

print(sum_divisors(0))
# 0
print(sum_divisors(3)) # Should sum of 1
# 1
print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18
# 55
print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51
# 114

3 Answers3

0

This should work:

def sum_divisors(n):
    sum = 0
    for i in range(1, int(n/2 + 1)):
        if (n % i) == 0:
            sum = sum + i

return sum

Be careful: xrange is used in Python 2 while range is Python 3, more info at this other question.

overmach
  • 96
  • 2
  • 11
0

Use the sum() function to add a sequence.

And you only need to go up to the square root of the number, not half the number.

from math import sqrt

def sum_divisors(n):
    if n < 1:
        return 0
    return sum(i for i in range(int(sqrt(n))+1) if n % i == 0)
Barmar
  • 741,623
  • 53
  • 500
  • 612
0
def sum_divisors(n):
    sum = 0
    for i in range(n-1):
        i +=1
        if n%i == 0:
            sum += i
    return sum

this is quite simple and works