Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program to Print all Prime numbers in an Interval
Next article icon

Python Program for Efficient program to print all prime factors of a given number

Last Updated : 16 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a number n, write an efficient function to print all prime factors of n. 

For example, if the input number is 12, then output should be “2 2 3”. And if the input number is 315, then output should be “3 3 5 7”. Following are the steps to find all prime factors. 

1) While n is divisible by 2, print 2 and divide n by 2. 

2) After step 1, n must be odd. Now start a loop from i = 3 to square root of n. While i divides n, print i and divide n by i, increment i by 2 and continue. 

3) If n is a prime number and is greater than 2, then n will not become 1 by above two steps. So print n if it is greater than 2. 

Python




# Python program to print prime factors
 
import math
 
# A function to print all prime factors of
# a given number n
def primeFactors(n):
     
    # Print the number of two's that divide n
    while n % 2 == 0:
        print(2)
        n = n // 2
         
    # n must be odd at this point
    # so a skip of 2 ( i = i + 2) can be used
    for i in range(3,int(math.sqrt(n))+1,2):
         
        # while i divides n , print i ad divide n
        while n % i== 0:
            print(i)
            n = n // i
             
    # Condition if n is a prime
    # number greater than 2
    if n > 2:
        print(n)
         
# Driver Program to test above function
 
n = 315
primeFactors(n)
 
# This code is contributed by Harshit Agrawal
#Code Improved by Sarthak Shrivastava
 
 

Output:

3 3 5 7

Time complexity: O(sqrt(n))
Auxiliary space: O(1)

How does this work? 

The steps 1 and 2 take care of composite numbers and step 3 takes care of prime numbers. To prove that the complete algorithm works, we need to prove that steps 1 and 2 actually take care of composite numbers. This is clear that step 1 takes care of even numbers. And after step 1, all remaining prime factor must be odd (difference of two prime factors must be at least 2), this explains why i is incremented by 2. 

Now the main part is, the loop runs till square root of n not till n. 

To prove that this optimization works, let us consider the following property of composite numbers. 

Every composite number has at least one prime factor less than or equal to square root of itself. 

This property can be proved using counter statement. Let a and b be two factors of n such that a*b = n. If both are greater than √n, then a.b > √n, * √n, which contradicts the expression “a * b = n”.

 In step 2 of the above algorithm, we run a loop and do following in loop 

a) Find the least prime factor i (must be less than √n,) 

b) Remove all occurrences i from n by repeatedly dividing n by i. 

c) Repeat steps a and b for divided n and i = i + 2. The steps a and b are repeated till n becomes either 1 or a prime number. Please refer complete article on Efficient program to print all prime factors of a given number for more details!

Approach#2: Using Sieve of Eratosthenes

This approach prints all the prime factors of a given number ‘n’. It first initializes an array ‘spf’ with indices from 0 to n+1 with values set to 0. It then assigns the value of ‘i’ to the corresponding index in the array for all ‘i’ from 2 to n. For even numbers, the value of 2 is assigned to the corresponding index in the array. Then, for all odd numbers ‘i’ from 3 to the square root of ‘n’, the array index ‘spf[i]’ is checked, and if it equals to ‘i’, then all multiples of ‘i’ in the range from ‘i*i’ to ‘n’ are checked and their corresponding array values are set to ‘i’. Finally, the prime factors of the given number are printed using the array ‘spf’.

Algorithm

1. Create a boolean array “prime[0..n]” and initialize all entries it as true.
2. Mark all the multiples of 2, 3, 5, …, sqrt(n) as not prime. Here, instead of marking, we store the smallest prime factor for every composite number.
3. Traverse the array from smallest prime factor of i to sqrt(n) while i divides n. The smallest prime factor of n will be a prime factor.
4. If n is a prime number and greater than 2, then n will not become 1 by above two steps. So print n if it is greater than 2.

Python3




def primeFactors(n):
    spf = [0 for i in range(n+1)]
    spf[1] = 1
    for i in range(2, n+1):
        spf[i] = i
    for i in range(4, n+1, 2):
        spf[i] = 2
  
    for i in range(3, int(n**0.5)+1):
        if spf[i] == i:
            for j in range(i*i, n+1, i):
                if spf[j] == j:
                    spf[j] = i
                      
    while n != 1:
        print(spf[n], end=" ")
        n = n // spf[n]
  
# example usage
n = 315
primeFactors(n)
 
 
Output
3 3 5 7 

Time Complexity: O(n*log(log(n)))
Space Complexity: O(n)

Approach#3: Using anonymous function

The approach uses anonymous function to generate all prime factors of a given number. It then uses a while loop and for loop to repeatedly call the function and append the factors to a list until the given number n is reduced to 1. Finally, it prints the prime factors of n separated by a space.

Algorithm

1. Define an anonymous function prime_factors that takes a positive integer n as input and generates all prime factors of n.
2. Initialize an empty list factors.
3. Use a while loop to repeatedly call the prime_factors function and append the factors to factors until n is reduced to 1.
4. Inside the while loop, use a for loop to iterate over the prime factors of n generated by the prime_factors function.
5. Append each factor to factors and update n by dividing it by the factor.
6. Print the prime factors of n separated by a space using the print function with the * operator to unpack the list of factors as arguments.

Python3




# Using anonymous function
prime_factors = lambda n: [i for i in range(2, n+1) if n%i == 0 and all(i % j != 0 for j in range(2, int(i**0.5)+1))]
n = 315
factors = []
while n > 1:
    for factor in prime_factors(n):
        factors.append(factor)
        n //= factor
print(*factors)
 
 
Output
3 5 7 3

Time complexity: O(n^1.5)
Auxiliary Space: O(n) or O(log n)



Next Article
Python Program to Print all Prime numbers in an Interval
author
kartik
Improve
Article Tags :
  • Python Programs

Similar Reads

  • Python Program to Print all Prime numbers in an Interval
    The task of printing all prime numbers in an interval in Python involves taking two input values representing a range [x, y] and finding all prime numbers within that range. A prime number is a natural number greater than 1 that is divisible only by 1 and itself. For example, in the interval [2, 7],
    5 min read
  • Python Program for Number of elements with odd factors in given range
    Given a range [n,m], find the number of elements that have odd number of factors in the given range (n and m inclusive). Examples: Input : n = 5, m = 100 Output : 8 The numbers with odd factors are 9, 16, 25, 36, 49, 64, 81 and 100 Input : n = 8, m = 65 Output : 6 Input : n = 10, m = 23500 Output :
    2 min read
  • Python Program for Find sum of even factors of a number
    Given a number n, the task is to find the even factor sum of a number. Examples: Input : 30 Output : 48 Even dividers sum 2 + 6 + 10 + 30 = 48 Input : 18 Output : 26 Even dividers sum 2 + 6 + 18 = 26 Let p1, p2, … pk be prime factors of n. Let a1, a2, .. ak be highest powers of p1, p2, .. pk respect
    4 min read
  • Python Program to print all the numbers divisible by 3 and 5 for a given number
    Given the integer N, the task is to print all the numbers less than N, which are divisible by 3 and 5.Examples : Input : 50Output : 0 15 30 45 Input : 100Output : 0 15 30 45 60 75 90 Approach: For example, let's take N = 20 as a limit, then the program should print all numbers less than 20 which are
    2 min read
  • Python Program to Print All Pronic Numbers Between 1 and 100
    Pronic numbers are also called oblong numbers or rectangular numbers. They are produced by multiplying two successive integers. Mathematically, it can be written as n * (n + 1), where n is a positive integer. For instance, 6 is a pronic number because it equals 2 * (2 + 1). Similarly, when you multi
    2 min read
  • Python Program for Find minimum sum of factors of number
    Given a number, find minimum sum of its factors.Examples: Input : 12Output : 7Explanation: Following are different ways to factorize 12 andsum of factors in different ways.12 = 12 * 1 = 12 + 1 = 1312 = 2 * 6 = 2 + 6 = 812 = 3 * 4 = 3 + 4 = 712 = 2 * 2 * 3 = 2 + 2 + 3 = 7Therefore minimum sum is 7Inp
    1 min read
  • Python Program to Reverse all Prime Numbers in Array Without Affecting Elements
    Given an array, our task is to Reverse all prime numbers in an array without affecting other elements in Python. Examples: Input : arr = {1, 2, 3, 4, 5, 6}Output : {1,5,3,4,2,6}Explanation: Prime elements in given array are 2,3,5. After reversing the modified array will be {1,5,3,4,2,6}Approach: Sta
    3 min read
  • Python Program to Find Numbers Divisible by Another Number
    We are given a list of numbers and a number. We have to find all the numbers in the list that are divisible by the given single number. Examples: Input: list=[8, 14, 21, 36, 43], num=3Output: 21, 36, 57Input: list=[2, 17, 25, 31, 48, 55], num=5Output: 25, 55In this article, we will discuss the diffe
    3 min read
  • Python program to find the factorial of a number using recursion
    A factorial is positive integer n, and denoted by n!. Then the product of all positive integers less than or equal to n. [Tex]n! = n*(n-1)*(n-2)*(n-3)*....*1 [/Tex] For example: [Tex]5! = 5*4*3*2*1 = 120 [/Tex] In this article, we are going to calculate the factorial of a number using recursion. Exa
    1 min read
  • Python Program to Find LCM of Two Numbers
    We are given two numbers and our task is to find the LCM of two numbers in Python. In this article, we'll discuss different approaches to finding the LCM of two numbers in Python. Example: Input: a = 12, b = 15Output: 60Explanation: LCM of 12 and 15 is 60Python Program to Find LCM of Two NumbersBelo
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences