Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Find the Factors of a Number (Solution)

00:00 I’m back over in a new file in IDLE and with a short task description. I want to display all the factors of a number chosen by the user. So I want to start by allowing the user to choose a number and assign that to a variable. num is input() by the user, where I’ll say "Enter a positive integer".

00:22 And then I want to convert that to an integer, right? Because the input is going to be a string. So I’ll wrap that into a call to int(). And keep in mind, in this current form, this is going to fail if the user inputs anything other than an integer.

00:35 So there’s ways that you could fix that, that you’ve seen before. I’m not going to do it right now. So let’s first get the basic functionality done of this. All right, so now I know that I want to go over all the numbers up to that specific number that the user inputs, and that sounds like a loop.

00:51 So we’ll start with a for loop. for every divisor in a range() that starts from 1 and goes up to the number that the user entered plus one.

01:04 Keep in mind that the range otherwise doesn’t include the number that you need, so I’m going to say num + 1. And now I want to do something in here.

01:13 Let’s put in a comment for now: I want to figure out what’s the factor,

01:19 which numbers are factors.

01:24 And you’ve actually done something like that before, and you’ve used the modulo operator (%) for it. So it can say if the num that is entered % the divisor

01:37 is equal to 0—that means there’s no remainder—then you want to print out the message, and the message is going to be that whatever that number is, that it’s currently looping over is a factor of the number that the user put in. You can do that using an f-string:

01:59 f"{divisor} is a factor of {num}". Okay, this looks good to me. Let’s give it a spin.

02:14 Save it. Enter a positive integer, so I’m going to say 12, like in the example. And then you can see 1, 2, 3, 4, 6, and 12 are all factors of 12.

02:24 And that’s the same output that we’ve already seen in the task description. We can try something else. Let’s run it again.

02:34 Positive integer 6. 1, 2, 3, and 6 are all factors of 6. Great. So this is a possible solution that works.

02:43 Keep in mind that if the user inputs something that isn’t a positive integer, then this is not going to work. So you could enhance this little program by putting in some error handling, for example. But for now, I’m happy with this solution.

02:58 So, I’ll just clean up the comment here, and let’s move over here. Here’s the possible solution. The code is a little more concise, so num is the input("Enter a positive integer: ") converted to an integer.

03:12 And then for divisor in range(1, num + 1): if num % divisor has no remainder, then print out this message. And that’s it. Ian, we solved the challenge. Yippee!

Anonymous on Feb. 15, 2024

A different approach that uses the square root approach, i added comments for myself, i’m not a match genius so there might be some small errors here and there

from math import sqrt

def find_factors(n: int) -> list[int]:
    factors = []  # Create a list that will hold all the factors of n

    # Calculate the floor of n square root
    square_root = int(sqrt(n))  # upper bound limit

    # Any number <= to the square root, there exist a factor n/i
    # that is >= to the square root of n
    i = 1
    while i <= square_root:
         # check if n is divisible by i
         if n % i == 0:

            # if n / i is equal to the square root
            # we dont add n/i to the the list of factors
            # n is a perfect square and n/i == i, this avoids duplication
            if n / i == i:
                factors.append(i)
            else:
                # since i is not the square root of n
                # we have a distinct factors of i and n/i
                factors.extend([i, int(n/i)])
            i += 1

    # (1, 12) i, n/i
    # (2, 6)  i, n/i
    # (3, 4)  i, n/i
    return sorted(factors)


number = int(input('Enter a positive integer: '))
factors = find_factors(number)

for i in factors:
    print('{} is a factor of {}'.format(i, number))

Anonymous on Feb. 15, 2024

Made a little mistake, i += 1 is nested wrong, it should be outside the if statements and the if statement should be one space less otherwise it would not match with the indentation of i += 1.

Probably made the mistake while testing and writing the comments :)

Become a Member to join the conversation.