Eugene
Eugene

Reputation: 237

Sum the factors of a number (excluding the number itself)

After I edited my code, I understand how to do it:

def sum_factors(n):
  sum = 0
  factor = 1
  # Return the sum of all factors of n, not including n
  while n!=0 and factor < n:
    if n % factor == 0:
        sum = sum + factor
        factor = factor + 1
    else:
        factor = factor + 1
  return sum

My initial code could not sum the factors but I don't understand why:

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

Could you please explain why my initial code didn't work?

Upvotes: 1

Views: 2375

Answers (3)

user3657941
user3657941

Reputation:

Sometimes, it helps to add some debugging output to a Python program:

def sum_divisors(n):
    sum = 0
    factor = 1
    # Return the sum of all divisors of n, not including n
    print(f"factor = {factor}")
    while n % factor == 0 and factor < n:
        sum = sum + factor
        factor = factor + 1
        print(f"factor = {factor}")
    return sum

print(sum_divisors(30))

Output

factor = 1
factor = 2
factor = 3
factor = 4
6

Notes

As we can see, the while loop exits when it finds a number that is not a factor.

Refactoring

I noticed that you have duplicate code in your if-else block. Whenever this happens, you can move the common code outside:

    if n % factor == 0:
        sum = sum + factor
    factor = factor + 1

Upvotes: 1

Avaye Dawadi
Avaye Dawadi

Reputation: 96

Your while loop writes

while n % factor == 0 and factor < n:

This would mean that once n % factor test condition is false, the code will break out of the while loop.

Let's use 10 as an example.

10 % 1 equals zero and 10 % 2 equals 0. But 10 % 3 does not equal 0. This means we break out of the while loop once factor gets to 3.

The answer we get would then be the sum of 1 and 2 which would be incorrect.

Upvotes: 1

Teera
Teera

Reputation: 26

The initial code put a strong emphasize on the condition while n % factor == 0 which is not a necessary condition to end the while loop.

Upvotes: 1

Related Questions