×

Python Prime factorization

Python Prime factorization

In this tutorial, we will design a program where we will find all the prime factors of a number. Then, we will print all these prime factors of the given number in the output of the number.

A Python program to find all the prime factors of any number

Before proceeding with the Python program, look at the following example:

  • Prime factor of 105: 3, 5, 7
  • Prime factor of 246: 2, 3, 41 etc.

Following are the key steps for program:

1). When the given number is divisible by 2, we should print 2 in output and divide the number by 2. We have to follow this step until the number is no more divisible by 2.

2). After completing the step 1, the given number is now must be odd. Now, we have to start for loop on the resultant number from step 1, from i = 3 to square root of the given number. Print i integer in output everytime when i divides the resultant number.

3). When number is not divisible by i, print the remaining resultant number in the output.

This will be the prime factors of a given number in the program.

Note

We also have to add a condition where the number given by user maybe a prime number in itself. So, for this case we have to write if condition statement in the program where the given number should be greater than 1.

Now, look at the following program to find all the prime factors of a number and after running the following program we will understand it's working and functioning in detail:

Example –

 # Importing math module in Python
 import math
 # Design a function PrimeFactorization for prime factors of number
 def PrimeFactorization(a):
 # Use the while loop for checking divisibility by 2
             while a % 2 == 0:
                         print (2), # printing 2 until condition become false
                         a = a / 2
             # Using a for loop withsqrt() function of math module  
             for b in range(3,int(math.sqrt(a))+1,2):
 # Using a while loop inside for loop
                         while a % b == 0:
                                     print (b), # printing all odd prime factors
                                     a = a / b
             # Using the if condition
             if a > 2:
                         print (a) # if condition satisfies it will print original number
 # Take a positive prime number from user
 a = int(input("Enter a positive integer number: "))
 # Print all prime factors of given number
 print("The prime factors are : ")
 PrimeFactorization(a) # calling out PrimeFactorization function 

Output:

 Enter a positive integer number: 25515
 The prime factors are:
 3
 3
 3
 3
 3
 3
 5
 7 

Working of the program:

Now, let's understand how the program works so that we know how with this program Python finding the prime factors of any given number.

  • We designed a PrimeFactorization function, where we perform operations on number given by user.
  • First, we used a while loop to follow the step 1, and divided the number by 2 until the condition 'a % 2 = 0' becomes false. We printed the 2 in output everytime while loop runs i.e., print(a).
  • When the condition becomes false, it means we know that now the resultant number is odd.
  • Now, we used for loop in the second step and assigned a = b. Then, we used the while loop to follow the condition, from b = 3 to square root of a. It will print all the odd prime factors of number a with print(b) statement.
  • After that, we have also used to if statement condition to check the condition that given number by user is greater than 1.
  • Then, we defined variable a and store the number in it that user will provide while running the program.
  • After that, we called out the PrimeFactorization function and provided argument 'a' in the function. It will print all the prime factors of number in the output when we run the program.

Related Topics

Data Structures and Algorithms using Python | Part 2

Files: A file is a location or information stored in computer storage devices. File handling is essential when the information or the data is to be held permanently. When we try to...

20 minutes read.

How to Pass a list as an Argument in Python

Lists in Python A list is a datatype in python which is used to store the data in a sequence. The lists are mutable; that is, we can change the values...

3 minutes read.

Python Project Ideas for Beginners

Python project ideas for beginners Advanced Python is an amazing platform to grow and achieve success as a developer in the future. Python is a programming language that can be very...

7 minutes read.

Python datetime

Python provides a module named datetime to work with the date and time. Sometimes in the real life application development, we need to work with the date and time. The date is...

3 minutes read.

Python program to find the area of the triangle

Python program to find the area of the triangle This article will discuss how to find the area of a triangle in Python with all three given sides. The area of...

2 minutes read.

Confusion Matrix Visualization Python

The confusion matrix is a two-dimensional array that compares the anticipated and actual category labels. These are the True Positive, True Negative, False Positive, and False Negative classification categories for...

4 minutes read.

Python Project Ideas Based On Django

Introduction If you have learned Python and you are an expert in Django, then your practical skills should be excellent in this field. If you want to check your practical skills,...

9 minutes read.

How to append a string in python

Adding or appending a string to another string is easy in Python. It is called concatenation and is a basic concept of strings in almost all programming languages. Ways to Append...

4 minutes read.

Python open() function

Python open() function The open() function in Python opens a file and returns a corresponding file object. If the file cannot be opened, an OSError is raised. Syntax open(file, mode='r', buffering=1, encoding=None, errors=None, newline=None, closefd=True, opener=None) Parameter file It represents the path and name of the file mode...

2 minutes read.

Python Project Ideas for Advanced Developers

Best Python Project Ideas for Advanced Developers Python is an object-oriented, high-level, interpreted programming language created by a developer known Guido Van Rossum. Python is one of the languages that gathered...

9 minutes read.

List Comprehension in Python

Sometimes we need new lists that are completely based on previously existing lists, so to perform this operation successfully, some of the programming languages come with a syntactic construct known...

5 minutes read.

Text detection using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python Marshmallow

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Cross Entropy in Python

Introduction Cross-entropy loss is frequently combined with the softmax function. Determine the total entropy among the distributions or the cross-entropy, which is the difference between two probability distributions. For the purpose...

5 minutes read.

Python String rstrip() method

Python String rstrip() method The string.rstrip() method in Python returns a copy of the string with trailing characters removed. Syntax string.rstrip([chars]) Parameter chars:  This argument represents a string specifying the set of characters to be...

1 minute read.

Python String isdigit() method

Python String isdigit() method The string.isdigit() method returns a boolean value true if all characters in the string are digits else for any other value it returns false. Syntax string.isdigit() Parameter NA Return This method returns a...

2 minutes read.

Captcha Code in Python with Example

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

To Do GUI Application using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

Sklearn linear Model in Python

The most effective and reliable Python machine learning library is Sklearn. Through a Python consistency interface, it offers a variety of effective tools for statistical modeling and machine learning, including...

5 minutes read.

XXhash Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

6 minutes read.