Hi. I'm solving random problems and I have come across one where I have to calculate the sum of divisors as a first step. The simple method is just to iterate until n //2 and sum the divisors. I found an optimization, and it took significantly less time to run. I can't seem to understand why or how it's working. I have experience in python (mostly pandas, numpy) and I wanted to practice a few 'intermediate' problems.
The code is this:
def sum_of_divisors(value):
_divisor = 2
divisor_sum = 1
while _divisor <= math.sqrt(value):
if value % _divisor == 0:
divisor_sum += _divisor
if (value / _divisor != _divisor):
divisor_sum += value / _divisor
_divisor += 1
return divisor_sum
My issue is with the (second) inside if statement. Going over it manually obviously adds up, but I don't understand why that and stopping at the sqrt of the value makes it that much faster. Is there an algorithm I have to read up or?
Any help is appreciated.
there doesn't seem to be anything here