Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The expectation of this problem: Returns the sum of all the divisors of a number, without including it.

I have seen this problem and how it solved. But actually, I could not get it after reviewed again and again. One of the main issues, I could not understand the problem clearly. I hope someone can explain to me this problem and solution in a simple way.

Edit: I just copied my code here instead of the image. Thank you for the warning.

def sum_divisors(n):
  sum = 1
  # Return the sum of all divisors of n, not including n
  div = 2
  if n == 0:
    return 0
  
  while div < n/2+1:
    if n % div == 0:
      sum += div
    div += 1
return sum

print(sum_divisors(6)) # Should be 6 (sum of 1+2+3)
print(sum_divisors(12)) # Should be 16 (sum of 1+2+3+4+6)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
201 views
Welcome To Ask or Share your Answers For Others

1 Answer

For the sum, first you have to consider only the numbers which completely divides the given number. This will range between 1 until half of the given number. For example if given number is 100, any number greater than 50 can't divide it completely, so the loop runs between 1 to 50, including 50.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...