Find integers that divides maximum number of elements of the array | CPP implementation of the approach ; Function to print the integers that divide the maximum number of elements from the array ; Initialize two lists to store rank and factors ; Start from 2 till the maximum element in arr ; Initialize a variable to count the number of elements it is a factor of ; Maximum rank in the rank list ; Print all the elements with rank m ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maximumFactor ( vector < int > arr ) { int n = arr . size ( ) ; vector < int > rank ; vector < int > factors ; int max = * max_element ( arr . begin ( ) , arr . end ( ) ) ; for ( int i = 2 ; i <= max ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ j ] % i == 0 ) count += 1 ; rank . push_back ( count ) ; factors . push_back ( i ) ; } } int m = * max_element ( rank . begin ( ) , rank . end ( ) ) ; for ( int i = 0 ; i < rank . size ( ) ; i ++ ) { if ( rank [ i ] == m ) cout << factors [ i ] << " ▁ " ; } } int main ( ) { vector < int > arr = { 120 , 15 , 24 , 63 , 18 } ; maximumFactor ( arr ) ; }