- Related Questions & Answers
- Add minimum number to an array so that the sum becomes even in C programming
- C Program for Tower of Hanoi
- C++ Program for Dijkstra’s shortest path algorithm?
- C/C++ Program for nth Catalan Number?
- C Program to Multiply two Floating Point Numbers?
- C program to find the length of a string?
- C Program to Check if all digits of a number divide it
- C Program to Check if a Given String is a Palindrome?
- Concatenate a string given number of times in C++ programming
- Write a program to Delete a Tree in C programming
- Write a C program to print “ Tutorials Point ” without using a semicolon
- Superperfect Number in C programming
- Super Prime in c programming
- Sum of the nodes of a Singly Linked List in C Program
- Sum of first n natural numbers in C Program

In this article, we will learn about the solution to the problem statement given below −

**Problem statement** − Given a number n, we need to find the product of all of its unique prime factors available and return it.

**For 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.

Using a for loop from i = 2 to n+1 check whether i is a factor of n & then check if i is the prime number itself, if yes then store product in product variable and continue this process until I become = n.

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 # main n = 18 print (productPrimeFactors(n))

6

The scope of all the variables are shown in the image below −

While n is divisible by 2(even), print 2 and divide n by 2.

After step 1, n must become odd. Now start a for loop from i = 3 till the square root of n. While I divides n, print I and divide n by i. After I fail to divide n, increment I by 2 and continue the process.

If n is a prime number and is greater than 2, then n will not become 1 by above two steps. Hence print n if it is greater than 2.

import math def productPrimeFactors(n): product = 1 # prime factor 2 if (n % 2 == 0): product *= 2 while (n%2 == 0): n = n/2 # n must be odd for i in range (3, int(math.sqrt(n)), 2): # While i divides n, print i and # divide n if (n % i == 0): product = product * i while (n%i == 0): n = n/i # n is a prime number greater than 2 if (n > 2): product = product * n return product # main() n = 8 print (int(productPrimeFactors(n)))

2

The scopes of the variables are mentioned in the image below −

In this article, we learned about the product of unique prime factors of a given number with a brute force approach and an efficient approach.

Advertisements