Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program for Product of unique prime factors of a number
In this article, we will learn how to find the product of all unique prime factors of a given number. For example, if the number is 12, its prime factors are 2 and 3, so the product would be 2 × 3 = 6.
Problem statement ? Given a number n, we need to find the product of all of its unique prime factors and return it.
Example
Input: num = 11 Output: Product is 11 Explanation: Here, the input number is 11 having only 1 prime factor and it is 11. And hence their product is 11. Input: num = 12 Output: Product is 6 Explanation: Prime factors of 12 are 2 and 3. Product = 2 × 3 = 6
Using Brute Force Approach
This approach checks each number from 2 to n to see if it's a factor, then verifies if it's prime ?
def productPrimeFactors(n):
product = 1
for i in range(2, n+1):
if (n % i == 0):
isPrime = 1
for j in range(2, int(i/2 + 1)):
if (i % j == 0):
isPrime = 0
break
if (isPrime):
product = product * i
return product
# Test the function
n = 18
print("Product of unique prime factors:", productPrimeFactors(n))
Product of unique prime factors: 6
Using Efficient Approach
This optimized method handles even numbers first, then checks only odd numbers up to the square root ?
import math
def productPrimeFactors(n):
product = 1
# Handle prime factor 2
if (n % 2 == 0):
product *= 2
while (n % 2 == 0):
n = n // 2
# n must be odd now, so check odd numbers from 3
for i in range(3, int(math.sqrt(n)) + 1, 2):
if (n % i == 0):
product = product * i
while (n % i == 0):
n = n // i
# If n is a prime number greater than 2
if (n > 2):
product = product * n
return product
# Test the function
n = 12
print("Product of unique prime factors:", productPrimeFactors(n))
n = 30
print("Product of unique prime factors:", productPrimeFactors(n))
Product of unique prime factors: 6 Product of unique prime factors: 30
How It Works
The efficient approach works in three steps:
- Handle factor 2: If the number is even, multiply the product by 2 and divide out all powers of 2
- Check odd factors: Loop through odd numbers from 3 to ?n, and for each factor found, multiply it to the product once
- Handle remaining prime: If n becomes greater than 2 after the above steps, it's a prime factor itself
Comparison
| Approach | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Brute Force | O(n²) | O(1) | Small numbers |
| Efficient | O(?n) | O(1) | Large numbers |
Conclusion
The efficient approach using square root optimization is significantly faster for large numbers. It handles even factors separately and then checks only odd potential factors up to ?n, making it much more efficient than the brute force method.
