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


The unique prime factors is a factor of the number that is a prime number too. In this problem, we have to find the product of all unique prime factors of a number. A prime number is a number that has only two factors, the number and one.

Here we will try to find the best way to calculate the product of unique prime factors of a number. let's take an example to make the problem more clear.

There is a number say n = 1092, we have to get the product of unique prime factors of this. The prime factors of 1092 are 2, 3, 7, 13 there product is 546.

2 to find this an easy approach will be to find all the factors of the number and check if the factor is a prime number. if it then multiplies it to the number and then returns the multiply variable.

Input: n = 10
Output: 10

Explanation

Here, the input number is 10 having only 2 prime factors and they are 5 and 2.

And hence their product is 10.

Using a loop from i = 2 to n and check if i is a factor of n then check if i is the prime number itself if yes then store the product in product variable and continue this process till i = n.

Example

#include <iostream>
using namespace std;
int main() {
   int n = 10;
   long long int product = 1;
   for (int i = 2; i <= n; i++) {
      if (n % i == 0) {
         int isPrime = 1;
         for (int j = 2; j <= i / 2; j++) {
            if (i % j == 0) {
               isPrime = 0;
               break;
            }
         }
         if (isPrime) {
            product = product * i;
         }
      }
   }
   cout << product;
   return 0;
}

Updated on: 19-Aug-2019

262 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements