Find a number that divides maximum array elements | CPP program to find a number that divides maximum array elements ; stores smallest prime factor for every number ; Calculating SPF ( Smallest Prime Factor ) for every number till MAXN . Time Complexity : O ( nloglogn ) ; marking smallest prime factor for every number to be itself . ; separately marking spf for every even number as 2 ; checking if i is prime ; marking SPF for all numbers divisible by i ; marking spf [ j ] if it is not previously marked ; A O ( log n ) function returning primefactorization by dividing by smallest prime factor at every step ; Function to find a number that divides maximum array elements ; precalculating Smallest Prime Factor ; Hash to store frequency of each divisors ; Traverse the array and get spf of each element ; calling getFactorization function ; Returns Set view ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAXN  100001 NEW_LINE int spf [ MAXN ] ; void sieve ( ) { spf [ 1 ] = 1 ; for ( int i = 2 ; i < MAXN ; i ++ ) spf [ i ] = i ; for ( int i = 4 ; i < MAXN ; i += 2 ) spf [ i ] = 2 ; for ( int i = 3 ; i * i < MAXN ; i ++ ) { if ( spf [ i ] == i ) { for ( int j = i * i ; j < MAXN ; j += i ) if ( spf [ j ] == j ) spf [ j ] = i ; } } } vector < int > getFactorization ( int x ) { vector < int > ret ; while ( x != 1 ) { int temp = spf [ x ] ; ret . push_back ( temp ) ; while ( x % temp == 0 ) x = x / temp ; } return ret ; } int maxElement ( int A [ ] , int n ) { sieve ( ) ; map < int , int > m ; for ( int i = 0 ; i < n ; ++ i ) { vector < int > p = getFactorization ( A [ i ] ) ; for ( int i = 0 ; i < p . size ( ) ; i ++ ) m [ p [ i ] ] ++ ; } int cnt = 0 , ans = 1e+7 ; for ( auto i : m ) { if ( i . second >= cnt ) { cnt = i . second ; ans > i . first ? ans = i . first : ans = ans ; } } return ans ; } int main ( ) { int A [ ] = { 2 , 5 , 10 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << maxElement ( A , n ) ; return 0 ; }