Home >Backend Development >C++ >C/C++ program to find the product of the unique prime factors of a number

C/C++ program to find the product of the unique prime factors of a number

PHPz
PHPzforward
2023-09-18 10:01:02767browse

C/C++ program to find the product of the unique prime factors of a number

The only prime factor is also a factor of a prime number. In this problem, we have to find the product of all unique prime factors of a number. Prime number is a number with only two factors, a number and one.

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

There is a number n = 1092, and we must get the product of its unique prime factors. The prime factors of 1092 are 2, 3, 7, 13 and the product is 546.

2 An easy way to find this is to find all the factors of the number and check if the factor is a prime number. If it is then multiplied by a number then the multiplication variable is returned.

Input: n = 10
Output: 10

Explanation

Here, the entered number is 10, which has only 2 prime factors, which are 5 and 2.

So their product is 10.

Use a loop from i = 2 to n, check if i is a factor of n, then check if i is a prime number, if so, store the product in the product variable and continue this process until 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;
}

The above is the detailed content of C/C++ program to find the product of the unique prime factors of a number. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete