Print all numbers whose set of prime factors is a subset of the set of the prime factors of X in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a set of N numbers and a number X. And we have to print all numbers from the array whose set of prime factors is a subset of the set of prime factors of X.

Let’s take an example to understand the problem

Input: X= 30 , array = {2, 3, 6, 10, 12}
Output : 2 3 6

To solve this problem, we have to traverse elements of the array. And divide this element with gcd of (element, x). Repeat division till the gcd becomes 1. And print the remaining number.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void printPrimeSet(int a[], int n, int x){
   bool flag = false;
   for (int i = 0; i < n; i++) {
      int num = a[i];
      int g = __gcd(num, x);
      while (g != 1) {
         num /= g;
         g = __gcd(num, x);
      }
      if (num == 1) {
         flag = true;
         cout<<a[i]<<" ";
      }
   }
   if (!flag)
      cout << "There are no such numbers";
}
int main(){
   int x = 60;
   int a[] = { 2, 5, 10, 7, 17 };
   int n = sizeof(a) / sizeof(a[0]);
   cout<<"Numbers whose set of prime numbers is subset of set of prime factor of "<<x<<"\n";
   printPrimeSet(a, n, x);
   return 0;
}

Output

Numbers whose set of prime numbers is a subset of the set of prime factor of 60

2 5 10
raja
Published on 22-Jan-2020 09:53:24
Advertisements