In this post, we will write a Python program to find factors of a number with a detailed explanation and example.

But before we jump into the programming part, let’s understand the mathematical approach to finding factors of a given number.

How to Find Factors of a Given Number

Factors of a given number is a number that divides the given number without leaving any remainder.

For Example, the factors of 12 are 1, 2, 3, 4, 6, and 12 because these numbers divide 12 without leaving any remainder.

Now that we know how to find factors of a given number, let’s discuss how we can implement it in programming with the help of an algorithm.

Algorithm

  1. Take input from the user (num).
  2. Using loop iterate from 1 to num (for i in range(1,num+1)).
  3. Inside the loop check if num % i == 0 then print(i).
  4. End program

From the above Example and algorithm, we know how to implement a Python program to find factors of a given number.

But before writing the program here is a list of prerequisites that you have to know for this program.

Source Code

num = int(input("Enter a number: ")) 

print(f"Factors of {num} is :", end=" ") 
for i in range(1, num+1):
    if num % i == 0:
        print(i, end=",")

Output

Enter a number: 12
Factor of 12 is : 1,2,3,4,6,12,

We can also write the above program using a while-loop.

Python Program to Find Factors of a Number Using while loop

Before writing this program, there are a few programming concepts you need to know:

Source Code

num = int(input("Enter a number: ")) 

print(f"Factors of {num} is :", end=" ") 

i = 1
while i <= num:
    if num % i == 0:
        print(i,end=",")
    i = i+1

Output

Enter a number: 24
Factors of 24 is : 1,2,3,4,6,8,12,24,

For the practice of Python programming concepts let’s modify the above program and write it using Function.

Python Program to Find Factors of a Number Using Function

Before writing this program, there are a few programming concepts you need to know:

Source Code

def factors(n):
    for i in range(1,n+1): 
        if n % i == 0:
            print(i, end=",") 

num = int(input("Enter a number: ")) 

print(f"Factors of {num} is :", end=" ")  
factors(num) # Calling a Function

Output

Enter a number: 36
Factors of 36 is : 1,2,3,4,6,9,12,18,36,
Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

Write A Comment