I'm a python beginner and I'm trying to figure out the following below two python code samples. Both code looks same but printing a different result. The main function of the code is divisor summation.
CODE 1:
def divisor_sum(n):
no_div = 0
tot = int(n / 2) + 1
for i in range(1,tot):
if n % i == 0:
no_div += 1
print no_div
CODE 2:
def divisor2(m):
max_div = int(m / 2) + 1
val = 0
for x in range(1, max_div):
if m % x == 0:
val += x
print val
when calling the function?
divisor_sum(6)
divisor2(6)
Code ouput:
3
6
How it is producing two different results when both code samples are same?
3 Answers 3
Not exactly the same code:
CODE 1:
no_div += 1
CODE 2:
val += x
Comments
The first variant increments by 1 when a divisor is encountered:
no_div += 1
The second variant increments by the divisor:
val += x
This means that the first variant counts the number of divisors. The second variant sums the values of the divisors.
The divisors of 6 are 1, 2 and 3. So, there are a total of 3 divisors whose values sum to 6.
4 Comments
/ 2.Code in first function i.e divisor_sum() will be giving you the count of divisors of a number (then name of function is misleading). On the other hand code in the second function i.e divisor2() will give you sum of all the divisors of a number.
both function has different code :
divisor_sum() has : "no_div += 1 " that means increment no_div by 1 divisor2() has :"val += x" which means increment the value of val by x i.e if x=2 then val will become val+2.