C/C++ Program to find Product of unique prime factors of a number?

In this section we will see how we can get the product of unique prime factors of a number in an efficient way. There is a number say n = 1092, we have to get product of unique prime factors of this. The prime factors of 1092 are 2, 2, 3, 7, 13. So the unique prime factors are {2, 3, 7, 13}, and the product is 546.

Syntax

int uniquePrimeProduct(int n);

Algorithm

To solve this problem, we have to follow this approach −

  • Handle factor 2: When the number is divisible by 2, multiply 2 with product and divide the number by 2 repeatedly to skip duplicate 2s.
  • Handle odd factors: Starting from 3 to square root of the number, if the number is divisible by current value, multiply the factor into product and divide repeatedly to skip duplicates.
  • Handle remaining prime: If the number is greater than 2 after the loop, it is a prime factor itself.

Example

Here's a complete program to find the product of unique prime factors −

#include <stdio.h>
#include <math.h>

int uniquePrimeProduct(int n) {
    int i, prod = 1;
    
    /* Handle factor 2 */
    if (n % 2 == 0) {
        prod *= 2;
        n = n / 2;
    }
    while (n % 2 == 0) {  /* Skip next 2s */
        n = n / 2;
    }
    
    /* Handle odd factors from 3 to sqrt(n) */
    for (i = 3; i <= sqrt(n); i = i + 2) {
        if (n % i == 0) {
            prod *= i;
            n = n / i;
        }
        while (n % i == 0) {  /* Skip next i's */
            n = n / i;
        }
    }
    
    /* If n is still greater than 2, it's a prime factor */
    if (n > 2) {
        prod *= n;
    }
    
    return prod;
}

int main() {
    int n = 1092;
    printf("Number: %d\n", n);
    printf("Product of unique prime factors: %d\n", uniquePrimeProduct(n));
    
    /* Test with another number */
    n = 60;
    printf("\nNumber: %d\n", n);
    printf("Product of unique prime factors: %d\n", uniquePrimeProduct(n));
    
    return 0;
}
Number: 1092
Product of unique prime factors: 546

Number: 60
Product of unique prime factors: 30

How It Works

For n = 1092:

  • Prime factorization: 2² × 3 × 7 × 13
  • Unique prime factors: {2, 3, 7, 13}
  • Product: 2 × 3 × 7 × 13 = 546

For n = 60:

  • Prime factorization: 2² × 3 × 5
  • Unique prime factors: {2, 3, 5}
  • Product: 2 × 3 × 5 = 30

Key Points

  • The algorithm has O(?n) time complexity.
  • Each prime factor is counted only once, even if it appears multiple times.
  • The condition n > 2 at the end handles cases where the remaining number is a prime greater than ?n.

Conclusion

This efficient algorithm finds the product of unique prime factors by iterating only up to the square root of the number. It handles duplicate factors by dividing them out completely once found, ensuring each prime is multiplied only once.

Updated on: 2026-03-15T10:59:10+05:30

775 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements