How to Find Factors of a Number in Python

In mathematics, factors play an important role in various operations such as finding prime numbers, calculating greatest common divisors, and simplifying fractions. In this article, we learn about various methods used to calculate factors of a number in Python

Find Factors of a Number in Python

The factors of a number are calculated by checking a number that divides the original number without leaving a remainder. For instance, the factors of 10 are 1, 2, 5, and 10, which are obtained by dividing the original number by each integer from 1 to 10.

For Example:

1%10 yields 0 reminders, Similar 2,5,10 can able to divide the number 10 without any reminder, So these are called factors of number 10.

Since 3%10 yields a remainder of 1, 3 cannot be considered as a factor of 10.

Additionally, factors of a number can also be obtained by multiplying two integers whose product equals the original number, such as 1 x 10 = 10 or 2 x 5 = 10.

Finding Factors of a Number in Python

There are multiple methods used to find the factors of a number and below are the 3 easiest ways

  • Using For Loop
  • Using While Loop
  • Using math.sqrt

Using For Loop

We will be finding the factors of a number using for loop and below is the Python code to achieve it

def find_factors(num): 
    factors = [] 
    for i in range(1, num + 1): 
        if num % i == 0: 
            factors.append(i) 
    return factors

print(find_factors(int(input(" Enter the number to find the factor: "))))

In the above code, we have defined a function called find_factors that takes an integer num as its argument and return the factors.

  1. This function initializes an empty list called factors that will later store all the factors of the given number.
  2. For loop is used to iterate over all the numbers from 1 to num + 1
  3. Each iteration Will check the current number is a factor of the input number, By using the modulo operator %, If it yields a reminder that it is not a factor and if the remainder is 0 then it will be added to the factors list

At last, the function returns the list of all the factors of the given number, We can print to see it in the console as shown.

Additionally, We have added an input() function to make it interactive by receiving the input number from the user

Output:

Enter the number to find the factor: 15
[1, 3, 5, 15]

For input 15, We have received the factors => 1, 3, 5, 15

Using While Loop

In this method, We will be using a while loop to calculate the factors, and below is the Python code to achieve it

def find_factors(num):
    factors = []
    i = 1
    while i <= num:
        if num % i == 0:
            factors.append(i)
        i += 1
    return factors


print(find_factors(int(input(" Enter the number to find the factor: "))))

Output:

 Enter the number to find the factor: 15
[1, 3, 5, 15]

In the above code, we have replaced the “for” loop with a “while” loop that iterates from 1 to num(Input number). The loop continues until “i” is greater than the input num.

Inside the loop,

  1. We will check whether “i” is a factor of “num“, and if Yes, we will append it to the “factors” list.

This method is very similar to the previous method, But the only change is we are using a “while” loop instead of a “for” loop, It has some advantages like

  • when you need more control over the loop iteration
  • when the loop condition is not based on a numerical range.

Using math.sqrt

One common method for finding all the factors of a number is to divide the number by each possible divisor starting from 1 up to the square root of the number. If the divisor is a factor, then both the divisor and the quotient are factors of the number.

Python Code:

import math

def find_factors(num):
    factors = []
    for i in range(1, int(math.sqrt(num))+1):
        if num % i == 0:
            factors.append(i)
            if num//i != i:
                factors.append(num//i)
    return factors



print(find_factors(int(input(" Enter the number to find the factor: "))))

Output:

 Enter the number to find the factor: 2343
[1, 2343, 3, 781, 11, 213, 33, 71]

In the above code, Initially, we imported the math module to use the sqrt() function which returns the square root of the given number. Then, we iterate over all the numbers from 1 to the square root of the given number using a for loop.

Inside the loop,

  1. We will check if the current number is a factor of the given input number. If Yes, we will add it to the factors list.
  2. Then, We will check if the quotient obtained by dividing the number by the current divisor is different from the divisor. If Yes, we will again add the quotient to the factors list as well.

This method is more efficient than the previous two methods in findings the factors because it only needs to iterate up to the square root of the given number. This method can help to gain more performance when dealing with large numbers, We also going to discuss the performance of all the methods in the upcoming topics

Performance Testing

We are going to do a quick test to find which is the best approach for all three, For that, I am doing some changes in the code below

import math

def find_factors_usingsqrt(num):
    factors = []
    loop=0
    for i in range(1, int(math.sqrt(num))+1):
        if num % i == 0:
            factors.append(i)
            if num//i != i:
                factors.append(num//i)
        loop += 1
     print(f"Number of Loops: {loop} ")
    return factors

def find_factors_usingloop(num):
    factors = []
    loop = 0
    for i in range(1, num + 1):
        if num % i == 0:
            factors.append(i)
        loop += 1
     print(f"Number of Loops: {loop} ")
    return factors


print(find_factors_usingsqrt(9999))
print(find_factors_usingloop(9999))

I have created 2 functions, find_factors_usingsqrt uses math.sqrt method and find_factors_usingloop uses the Loop method, I have added a variable called loop to check, How many loops is happening to find the factors

Output:

print(find_factors_usingsqrt(9999)) 

Number of Loops: 99
[1, 9999, 3, 3333, 9, 1111, 11, 909, 33, 303, 99, 101]


print(find_factors_usingloop(9999))

Number of Loops: 9999
[1, 3, 9, 11, 33, 99, 101, 303, 909, 1111, 3333, 9999]

Process finished with exit code 0

As we can clearly see the “math.sqrt” just used 99 loops and the normal Loop method used 9999 loops, So the winner is math.sqrt. Which is efficient

Conclusion

In conclusion, there are different ways to find the factors of a number in Python. Depending on your needs and the size of the number, you can choose the most appropriate approach to solve the problem efficiently. We also did a quick performance test to check which is more efficient with a large number and the recommendation is to use math.sqrt

Good Luck with our Learning !!

Related Topics

How to Calculate the Average of Numbers in Python

Defining and Calling a Function in Python

How to Nest a Dictionary in a List?

Similar Posts