Print array elements that are divisible by at-least one other in C++


In this problem, we are given an array of integers and we have to print only those numbers that are divisible by at least one other element of the array.

Let’s take an example to understand the concept better,

Input  : 3 12 16 21
Output : 12 21

Explanation − 3 is the smallest so it can be divisible by any other number are 12 which is divisible by 3, 16 not divisible by 3 and then 21 which is divisible by 3. So, we will neglect 3 and 16.

One easy way is to check if all elements are divisible by any other element of the array or not. But this is not the best possible solution for the problem.

Using hash can be a better solution. We will store elements of an array in hash and then find the max element of the array. And then up to this max elements find multiples of a given number and if multiple are found in hash then the element is divided by at least one element of the array. Like this, we will print the element that is divided by at least one element of the array.

Example

Now, based on this concept lets create a program −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void printDivisibleNumber(int arr[], int n){
   unordered_set<int> s;
   int maxElement = INT_MIN;
   for (int i = 0; i < n; i++) {
      s.insert(arr[i]);
      maxElement = max(maxElement, arr[i]);
   }
   unordered_set<int> res;
   for (int i = 0; i < n; i++) {
      if (arr[i] != 0) {
         for (int j = arr[i] * 2; j <= maxElement; j += arr[i]) {
            if (s.find(j) != s.end())
               res.insert(j);
            }
         }
      }
   unordered_map<int, int> mp;
   for (int i = 0; i <n; i++)
      mp[arr[i]]++;
   unordered_map<int, int>::iterator it;
   vector<int> ans;
   for (it = mp.begin(); it != mp.end(); it++) {
      if (it->second >= 2) {
         if (res.find(it->first) == res.end()) {
            int val = it->second;
            while (val--)
               ans.push_back(it->first);
         }
      }
      if (res.find(it->first) != res.end()) {
         int val = it->second;
         while (val--)
            ans.push_back(it->first);
      }
   }
   for (auto x : ans)
      cout<<x<<"\t";
}
int main(){
   int arr[] = {2, 4, 7 , 12 , 14 };
   int n = sizeof(arr) / sizeof(arr[0]);
   printDivisibleNumber(arr, n);
   return 0;
}

Output

12 14 4

Updated on: 03-Jan-2020

261 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements