Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with "while" looping

I have to somehow do a function in which when I execute it I will be able to add all the divisors of a number, in the way shown below.

This is getting me crazy, I have been in the same problem for about an hour.

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

print(sum_divisors(6)) # Should be 1+2+3=6
print(sum_divisors(12)) # Should be 1+2+3+4+6=16
like image 808
Miguel Estrada Avatar asked Sep 24 '26 21:09

Miguel Estrada


2 Answers

def sum_divisors(n): 
    sum = 0
    z = 1

    while n > z:
        if n % z == 0:
            sum = sum + z
            z = z + 1
        else:
            z = z + 1
    # Return the sum of all divisors of n, not including n
    return sum
like image 84
Girly Corner Avatar answered Sep 26 '26 11:09

Girly Corner


In your fonction, you return instantly after finding a divisor. That's why your fonction doesnt work Try to put each n%divisor == 0 in a list ans return it AT the end of the while.

Or try to print it directly.

like image 25
ChokMania Avatar answered Sep 26 '26 09:09

ChokMania



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!