1

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?

dreyescat
13.9k5 gold badges52 silver badges38 bronze badges
asked Oct 12, 2014 at 8:40

3 Answers 3

5

Not exactly the same code:

CODE 1:

no_div += 1

CODE 2:

val += x
answered Oct 12, 2014 at 8:43
Sign up to request clarification or add additional context in comments.

Comments

1

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.

answered Oct 12, 2014 at 8:50

4 Comments

This answer is a duplicate of the one given by @dreyescat
@David But for no of divisor for six is four and its printing 3. any idea ?
@Stux it doesn't include the number itself when counting divisors. That's the / 2.
I'm glad my explanations helped
0

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.

answered Oct 12, 2014 at 9:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.