Python Program for Efficient program to print all prime factors of a given number
Last Updated :
16 May, 2023
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
import math
def primeFactors(n):
while n % 2 = = 0 :
print ( 2 )
n = n / / 2
for i in range ( 3 , int (math.sqrt(n)) + 1 , 2 ):
while n % i = = 0 :
print (i)
n = n / / i
if n > 2 :
print (n)
n = 315
primeFactors(n)
|
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]
n = 315
primeFactors(n)
|
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
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)
|
Time complexity: O(n^1.5)
Auxiliary Space: O(n) or O(log n)
Similar Reads
Python Program for Product of unique prime factors of a number
Given a number n, we need to find the product of all of its unique prime factors. Prime factors: It is basically a factor of the number that is a prime number itself. Examples: Input: num = 10 Output: Product is 10 Explanation: Here, the input number is 10 having only 2 prime factors and they are 5
3 min read
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 largest prime factor of a number
Given a positive integer \'n\'( 1 <= n <= 1015). Find the largest prime factor of a number. Input: 6 Output: 3 Explanation Prime factor of 6 are- 2, 3 Largest of them is 3 Input: 15 Output: 5 C/C++ Code # Python3 code to find largest prime # factor of number import math # A function to find la
3 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
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
9 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 for Find sum of odd factors of a number
Given a number n, the task is to find the odd factor sum. Examples: Input : n = 30 Output : 24 Odd dividers sum 1 + 3 + 5 + 15 = 24 Input : 18 Output : 13 Odd dividers sum 1 + 3 + 9 = 13 Let p1, p2, ... pk be prime factors of n. Let a1, a2, .. ak be highest powers of p1, p2, .. pk respectively that
2 min read