Python Program for Product of Unique Prime Factors of a Number
Last Updated :
30 Oct, 2025
Given a number n, the task is to find the product of all its unique prime factors. A prime factor is a prime number that divides n exactly without leaving a remainder. For Examples:
Input: 10
Output: Product is 10
Explanation: prime factors of 10 are 2 and 5 and their product is 10.
Let's explore different methods to find the product of unique prime factors of a number in python.
Using SymPy Library
In this method, we use the built-in primefactors() function that directly returns a list of unique prime factors of a number. We then compute their product using math.prod().
Python
from sympy import primefactors
import math
n = 44
f = primefactors(n)
p = math.prod(f)
print(p)
Output
22
Using NumPy Product Function
This approach is similar to the SymPy method but uses numpy.prod() for computing the product efficiently when handling large factor lists.
Python
from sympy import primefactors
import numpy as np
n = 44
f = primefactors(n)
p = np.prod(f)
print(p)
Output
22
Using Math Module
In this method, we divide the number by 2 until it’s no longer divisible, then check divisibility by odd numbers up to its square root. Each prime divisor is multiplied only once to form the final product.
Python
import math
n = 44
p = 1
if n % 2 == 0:
p *= 2
while n % 2 == 0:
n //= 2
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
p *= i
while n % i == 0:
n //= i
if n > 2:
p *= n
print(p)
Explanation:
- Uses math.sqrt() to loop only up to the square root of n for efficiency and multiplies 2 once if it divides n.
- Checks odd divisors from 3 onwards and multiplies each distinct prime factor once.
- If a number greater than 2 remains, it’s a prime factor and multiplied at the end.
Using Iterative Division
In this method, we check each number from 2 to n. If it divides n, we check whether it’s prime by testing divisibility up to its half. Each prime divisor contributes once to the final product.
Python
n = 44
p = 1
for i in range(2, n + 1):
if n % i == 0:
res = True
for j in range(2, int(i / 2) + 1):
if i % j == 0:
res = False
break
if res:
p *= i
print(p)
Explanation:
- Iterates through all possible factors of n.
- For each factor, checks if it’s prime by trying to divide it by smaller numbers.
- Multiplies the factor with product only if it’s prime.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice