Find Product of Unique Prime Factors of a Number in Java



In this article, we will learn to calculate the product of the unique prime factors of a given number using Java. Prime factorization plays a crucial role in many mathematical and computational problems, and understanding how to work with prime factors can help you solve complex challenges efficiently. 

Problem Statement

Given a positive integer n, the task is to find the product of the unique prime factors of n. The objective is to calculate the product of all distinct prime factors of n that divide it exactly.

Input 

68

Output 

34

Since the unique prime factors of 68 are 2 and 17, and their product is 2 × 17 = 34.

Using a Simple Loop to Find Prime Factors

In the first approach, the program iterates through all integers from 2 to the given number, checks if each number is a divisor, and verifies whether it's prime. If the number is prime, we multiply it with the product of prime factors.

Following are the steps to calculate the product of the unique prime factors of a given number ?

  • Prime Factorization Logic: The method prime_factors(int num) checks each number from 2 to num to find divisors. For each divisor, it verifies whether it is prime.
  • Prime Check: For each divisor i, the program checks if it's prime by dividing it by numbers from 2 to i/2. If it's not divisible by any of these, it is considered prime.
  • Product Calculation: If i is prime and a divisor, the program multiplies it with the current product.

Example

To find the product of unique prime factors of a number the Java code is as follows ?

public class Demo {
   public static long prime_factors(int num){
      long my_prod = 1;
      for (int i = 2; i <= num; i++){
         if (num % i == 0){
            boolean is_prime = true;
            for (int j = 2; j <= i / 2; j++){
               if (i % j == 0){
                  is_prime = false;
                  break;
               }
            }
            if (is_prime){
               my_prod = my_prod * i;
            }
         }
      }
      return my_prod;
   }
   public static void main(String[] args){
      int num = 68;
      System.out.println("The product of unique prime factors is ");
      System.out.print(prime_factors(num));
   }
}

Output

The product of unique prime factors is
34

Optimized Method Using Prime Factorization

In this approach, we will use a more optimized method that reduces the number of operations by only checking for divisibility up to the square root of the number and keeping track of the unique prime factors.

Following are the steps to calculate the product of the unique prime factors of a given number ?

  • Efficient Prime Factorization: Instead of checking all numbers up to num, we check divisibility up to sqrt(num). This significantly reduces the number of checks.
  • Using a Set for Uniqueness: We use a HashSet to store prime factors. This ensures that unique prime factors are added, eliminating duplicates.
  • Handling Large Prime Numbers: If num is a prime number greater than 2 after the loop, we add it to the set.
  • Product Calculation: The prime factors stored in the set are multiplied together to compute the final product.

Example

To find the product of unique prime factors of a number the Java code is as follows ?

import java.util.HashSet;
public class OptimizedDemo {

    public static long prime_factors(int num) {
        HashSet<Integer> primeFactors = new HashSet<>();
        // Check for divisibility by 2
        while (num % 2 == 0) {
            primeFactors.add(2);
            num /= 2;
        }

        // Check for odd factors from 3 to sqrt(num)
        for (int i = 3; i * i <= num; i += 2) {
            while (num % i == 0) {
                primeFactors.add(i);
                num /= i;
            }
        }

        // If num is a prime number greater than 2
        if (num > 2) {
            primeFactors.add(num);
        }

        // Calculate the product of unique prime factors
        long product = 1;
        for (int prime : primeFactors) {
            product *= prime;
        }

        return product;
    }

    public static void main(String[] args) {
        int num = 68;
        System.out.println("The product of unique prime factors is ");
        System.out.print(prime_factors(num));  // Output the result
    }
}

Output

The product of unique prime factors is
34

Comparison Table

Criteria First Approach Optimized Approach
Time Complexity O(n * sqrt(n)) (due to checking divisibility and primality) O(sqrt(n)) (more efficient by reducing unnecessary checks)
Prime Check Method Checks divisibility for each divisor up to i/2 Only checks divisibility up to sqrt(n) for odd numbers
Memory Usage No additional data structures used Uses a HashSet to store unique prime factors
Handling Duplicates May include duplicate primes in the product Uses a HashSet to ensure only unique prime factors are multiplied
Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2024-12-23T18:10:06+05:30

575 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements