bahaaz bahaaz - 1 month ago 18
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

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

Answer

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:
            result.append(i)

    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.

Comments