Ali
Ali

Reputation: 133

Why does my divisors function not work in certain cases?

I have written this short function to calculate the number of factors a number has as a part of my program, however I have noticed that it does not work in certain cases.

Here is my code:

def divisors(n):
number_of_factors = 0

max_test_num = int(math.ceil(math.sqrt(n))+1)
for i in xrange(1,max_test_num):
    if n%i ==0:
        number_of_factors += 2
    if i*i == n:
        number_of_factors -= 1
return number_of_factors

Now if the number has a pair of divisors which are coprime, then the result returned is 2 too big.

For example, with input as 20, it returns 8, when the correct answer is 6.

Any suggestions on how to fix this or simply a better way to do this?

Thanks in advance

Upvotes: 0

Views: 41

Answers (1)

amit
amit

Reputation: 178431

max_test_num = int(math.ceil(math.sqrt(n))+1)

This makes you count elements twice, for example, with 20: ceil(sqrt(20))+1 = 5, so the condition if n%i ==0 applies for both 4 and 5, and for each you increase by 2.

The +1 in the mentioned line is redundant, remove it.

Upvotes: 1

Related Questions