4

I have a function that tells me the factors of a number, then should print how many it has.

factors = 0
def getFactors(n):
 global factors
 for i in range(1,n):
 if n%i==0:
 print(i)
 factors += 1
 print(n, "has", factors, "factors.")

However, the number of factors seems to be wrong. Apparently 16 has 6 factors even though it clearly lists 4.

>>> getFactors(16)
1
2
4
8
16 has 6 factors.
>>> 

What have I done wrong here?

asked Oct 14, 2015 at 12:45
1
  • You don't need to go the whole way to n. Obviously, a factor cannot be greater than n/2. Thus you can spare a half of iterations with range(1, n/2) Commented Oct 14, 2015 at 13:29

1 Answer 1

5

On the first time you call getFactors(16) you will correctly get 4. The problem is likely that you've called the function multiple times, and since you used global factors, the value of factors isn't reset to 0 each time you call the function. The global variable keeps being mutated each time you call the function.

If you remove the global variable and make it function local it will work fine

def getFactors(n):
 factors = 0
 for i in range(1,n):
 if n%i==0:
 print(i)
 factors += 1
 print(n, "has", factors, "factors.")
>>> getFactors(16)
1
2
4
8
16 has 4 factors.
answered Oct 14, 2015 at 12:47
Sign up to request clarification or add additional context in comments.

2 Comments

Brilliant. Thanks, I completely forgot it needed to be reset.
@Eddie If instead of printing the factors you want to return them, you can turn the function to one line as return [i for i in range(1,n) if n%i == 0] (or use yield, of course)

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.