Search code examples
pythonfunctionnumber-theory

Determining the number of integers with a certain amount of factors between two numbers


I would like to implement a function that takes as input three arguments (x, low, high) - all integers, and finds the number of integers that have x factors between low and high. For example, how many integers between 50 and 100 have 4 factors?

My code is as follows:

def n_factors(x, lower, upper):
""" Find how many integers have x (user-specified)
    factors from - lower to upper - (user-specified) """
    int_counter = 0 # integer counter
    div_count = 0 # divisor counter 
    for i in range(lower, upper+1):
        for j in range(2, i):
            if (i%j)==0:
                div_count += 1
        if (div_count == x):
            print i
            int_counter += 1
     return int_counter

When I try to run this I get incorrect results, e.g.

n_factors(2,10,20)
10
11
2

This should list the four prime numbers between 10 and 20 if the function worked but doesn't. Any help much appreciated!


Solution

  • You need to set div_count back to zero at the end of each iteration:

    def n_factors(x, lower, upper):
        int_counter = 0 # integer counter
        div_count = 0 # divisor counter
        for i in range(lower, upper+1):
            for j in range(1, i + 1):
                if (i%j)==0:
                    div_count += 1
            if div_count == x:
                print i
                int_counter += 1
            div_count = 0
        return int_counter