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

CServer Side ProgrammingProgrammingC++

In this section we will see how we can get the product of unique prime factor 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}, the product is 546. To solve this problem, we have to follow this rule −

  • When the number is divisible by 2, then multiply 2 with product, and divide the number by 2 repeatedly, then next 2s will be ignored.

  • Now the number must be odd. Now starting from 3 to square root of the number, if the number is divisible by current value, then multiply the factor into product, and change the number by divide it with the current number then continue. Next are ignored like above

  • And finally if the number is greater than 2, then it is not 1, so multiply the remaining number.

Let us see the algorithm to get better idea.

Algorithm

uniquePrimeProduct(n)

begin
   prod := 1
   if n is divisible by 2, then
      prod := prod * 2
      n := n / 2
   end if
   while n is divisible by 2, do
      n := n / 2
   done
   for i := 3 to √𝑛, increase i by 2, do
      if n is divisible by i, then
         prod := prod * i
         n := n / i
      end if
      while n is divisible by i, do
         n := n / i
      done
   done
   if n > 2, then
      prod := prod * n
   end if
end

Example

#include<stdio.h>
#include<math.h>
int uniquePrimeProduct(int n){
   int i, prod = 1;
   if(n % 2 == 0){
      prod *= 2;
      n = n/2;
   }
   while(n % 2 == 0){//skip next 2s
      n = n/2;
   }
   for(i = 3; i <= sqrt(n); i=i+2){ //i will increase by 2, to get only odd numbers
      if(n % i == 0){
         prod *= i;
         n = n/i;
      }
      while(n % i == 0){ //skip next i's
         n = n/i;
      }
   }
   if(n < 2){
      prod *= n;
   }
   return prod;
}
main() {
   int n;
   printf("Enter a number: ");
   scanf("%d", &n);
   printf("Product of prime factors: %d", uniquePrimeProduct(n));
}

Output

Enter a number: 1092
Product of prime factors: 546
raja
Published on 26-Jul-2019 11:28:35
Advertisements