bahaaz bahaaz - 1 year ago 100
Python Question

How many factors in an integer

I have to create a function that calculates how much factors an integer has. For example, when I call

the function should be able to tell me it has 4 factors (
). So where would I start off? Would do I need to put?

Answer Source

The % (modulus) operator gives you the remainder of a division. If that remainder is 0, then the second multiple is a factor of the second. So just loop through all the numbers from 1 to n and check if they're factors; if so, add them to the list with append:

def factors(n):
    result = []

    for i in range(1, n + 1):
        if n % i == 0:

    return result

Here's a demo.

Or, more concisely using lambdas:

def factors(n):
    return filter(lambda i: n % i == 0, range(1, n + 1))

Here's a demo.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download