We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

Here is a simple solution written in Python 3. Surprisingly, many other solutions I see don't realize you don't need to iterate though each number - only the first half.

def divisorSum(self, n):
if n == 1:
return 1
else:
factor_sum = 1 + n
for i in range(2, n//2 + 1):
if n % i == 0:
factor_sum += i
return factor_sum

You can do even better, if you compute the square root and use that as the limit you can further break down the numbers to check. Also odd numbers can't have even dividers:

def divisorSum(self, n):
if n == 1:
sum_div = 1
else:
sum_div = n + 1
limit = int(n**0.5) # math.sqrt(n)
if limit * limit == n:
sum_div += limit
limit -= 1
step_width = n % 2 + 1
current_div = 2
while current_div <= limit:
if n % current_div == 0:
# Add both divisors
sum_div += current_div + n//current_div
current_div += step_width
return sum_div

## Day 19: Interfaces

You are viewing a single comment's thread. Return to all comments →

Here is a simple solution written in Python 3. Surprisingly, many other solutions I see don't realize you don't need to iterate though each number - only the first half.

An elegant solution indeed. Thank you for sharing.

could you plz explain the code above? thank you

You can do even better, if you compute the square root and use that as the limit you can further break down the numbers to check. Also odd numbers can't have even dividers: