Find integers that divides maximum number of elements of the array in C++


In this problem, we are given an array arr[] of n integers.

Our task is to find integers that divides maximum number of elements of the array. 

Problem Description: We need to find a number p which can divide the maximum number of elements of the array. In case, there are more than one such element we will return the smaller one.

Let’s take an example to understand the problem, 

Input: arr[] = {4, 5, 6, 7, 8}

Output: 2

Explanation: 

The element 2 divides {4, 6, 8}.

Solution Approach

A simple solution to the problem is by looping through the array and then for each element of the array, divide each element from the array with elements from 1 to k. And return the element which divides the maximum number of elements of the array.

Another approach to solve the problem is by using the fact that all elements of the array are divided by the prime factors.

We will store the frequency of division by each prime number and then return factor with maximum frequency. We store the prime numbers and their frequencies in a hash.

Program to illustrate the working of our solution,

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;

#define MAXN 100001
int primes[MAXN];

void findPrimeSieve()
{
   primes[1] = 1;
   for (int i = 2; i < MAXN; i++)
      primes[i] = i;
   for (int i = 4; i < MAXN; i += 2)
      primes[i] = 2;

   for (int i = 3; i * i < MAXN; i++) {
      if (primes[i] == i) {
         for (int j = i * i; j < MAXN; j += i)
            if (primes[j] == j)
               primes[j] = i;
      }
   }
}

vector<int> findFactors(int num)
{
   vector<int> factors;
   while (num != 1) {
      int temp = primes[num];
      factors.push_back(temp);
      while (num % temp == 0)
         num = num / temp;
   }
   return factors;
}

int findmaxDivElement(int arr[], int n) {

   findPrimeSieve();
   map<int, int> factorFreq;
   for (int i = 0; i < n; ++i) {

      vector<int> p = findFactors(arr[i]);
      for (int i = 0; i < p.size(); i++)
         factorFreq[p[i]]++;
   }

   int cnt = 0, ans = 1e+7;
   for (auto itr : factorFreq) {
      if (itr.second >= cnt) {
         cnt = itr.second;
         ans > itr.first ? ans = itr.first : ans = ans;
      }
   }

   return ans;
}

int main() {

   int arr[] = { 4, 5, 6, 7, 8 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The number that divides the maximum elements of the array is "<<findmaxDivElement(arr, n);
   return 0;
}

Output

The number that divides the maximum elements of the array is 2

Updated on: 25-Jan-2021

231 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements