Search code examples
pythonfactors

Counting how many factors an integer has


So I have written a function to determine how many factors a number has and list that number. However my function is not outputting the correct information.

def num_factors(integer):
    result = 0
    for i in range(1,integer+1):
        if integer%i == 0:
            result +=1
    return result

print(num_factors(5))
print(num_factors(6))
print(num_factors(97))
print(num_factors(105))
print(num_factors(999))

For some reason it is outputting:

2
4
2
8
8

when it should be outputting:

0
2
0
6
6

Solution

  • With the line for i in range(1,integer+1): you are looping through all the numbers between 1 and your integer, including 1 and your integer, which are of course factors.

    So for example if integer = 5, you'd loop over 1, 2, 3, 4, and 5. Out of these 1 and 5 are both of course factors of 5.

    You could edit the line to for i in range(2,integer): to fix the error. The resulting code would look like this:

    def num_factors(integer):
        result = 0
        for i in range(2,integer):
            if integer%i == 0:
                result +=1
        return result
    
    print(num_factors(5))
    print(num_factors(6))
    print(num_factors(97))
    print(num_factors(105))
    print(num_factors(999))
    

    Though as someone in the comments suggested, you could reduce the search space even more.