Find a number that divides maximum array elements
Last Updated :
11 Jul, 2025
Given an array A[] of N non-negative integers. Find an Integer greater than 1, such that maximum array elements are divisible by it. In case of same answer print the smaller one.
Examples:
Input : A[] = { 2, 4, 5, 10, 8, 15, 16 };
Output : 2
Explanation: 2 divides [ 2, 4, 10, 8, 16] no other element divides greater than 5 numbers.'
Input : A[] = { 2, 5, 10 }
Output : 2
Explanation: 2 divides [2, 10] and 5 divides [5, 10], but 2 is smaller.
Brute Force Approach:
Brute force approach to solve this problem would be to iterate over all the numbers from 2 to the maximum element in the array and check if each number is a factor of all the elements in the array. We can keep track of the number that has the maximum number of factors and return that number.
Below is the implementation of the above approach:
C++
// CPP program to find a number that
// divides maximum array elements
#include <bits/stdc++.h>
using namespace std;
// Function to find a number that
// divides maximum array elements
int maxElement(int A[], int n)
{
int maxCount = 0, ans = 0;
for (int i = 2; i <= *max_element(A, A + n); i++) {
int count = 0;
for (int j = 0; j < n; j++) {
if (A[j] % i == 0) {
count++;
}
}
if (count > maxCount) {
maxCount = count;
ans = i;
}
}
return ans;
}
// Driver program
int main()
{
int A[] = { 2, 4, 5, 10, 8, 15, 16 };
int n = sizeof(A) / sizeof(A[0]);
cout << maxElement(A, n);
return 0;
}
Java
import java.util.*;
class Main
{
// Function to find a number that
// divides maximum array elements
static int maxElement(int[] A, int n) {
int maxCount = 0, ans = 0;
for (int i = 2; i <= Arrays.stream(A).max().getAsInt(); i++) {
int count = 0;
for (int j = 0; j < n; j++) {
if (A[j] % i == 0) {
count++;
}
}
if (count > maxCount) {
maxCount = count;
ans = i;
}
}
return ans;
}
// Driver program
public static void main(String[] args) {
int[] A = { 2, 4, 5, 10, 8, 15, 16 };
int n = A.length;
System.out.println(maxElement(A, n));
}
}
Python
# Python program to find a number that
# divides maximum array elements
import sys
# Function to find a number that
# divides maximum array elements
def maxElement(A, n):
maxCount = 0
ans = 0
for i in range(2, max(A) + 1):
count = 0
for j in range(n):
if A[j] % i == 0:
count += 1
if count > maxCount:
maxCount = count
ans = i
return ans
# Driver program
if __name__ == '__main__':
A = [2, 4, 5, 10, 8, 15, 16]
n = len(A)
print(maxElement(A, n))
C#
using System;
using System.Linq;
public class Program
{
// Function to find a number that
// divides maximum array elements
public static int MaxElement(int[] A, int n)
{
int maxCount = 0, ans = 0;
for (int i = 2; i <= A.Max(); i++)
{
int count = 0;
for (int j = 0; j < n; j++)
{
if (A[j] % i == 0)
{
count++;
}
}
if (count > maxCount)
{
maxCount = count;
ans = i;
}
}
return ans;
}
// Driver program
public static void Main()
{
int[] A = { 2, 4, 5, 10, 8, 15, 16 };
int n = A.Length;
Console.WriteLine(MaxElement(A, n));
}
}
JavaScript
// Function to find a number that
// divides maximum array elements
function maxElement(A) {
let maxCount = 0;
let ans = 0;
for (let i = 2; i <= Math.max(...A); i++) {
let count = 0;
for (let j = 0; j < A.length; j++) {
if (A[j] % i === 0) {
count++;
}
}
if (count > maxCount) {
maxCount = count;
ans = i;
}
}
return ans;
}
// Driver program
const A = [2, 4, 5, 10, 8, 15, 16];
const n = A.length;
console.log(maxElement(A));
Output: 2
Time Complexity: O(N^2)
Space Complexity: O(1)
Efficient Approach: We know that a number can be divisible only by elements which can be formed by their prime factors.
Thus we find the prime factors of all elements of the array and store their frequency in the hash. Finally, we return the element with maximum frequency among them.
You can use factorization-using-sieve to find prime factors in Log(n).
Below is the implementation of above approach:
C++
// CPP program to find a number that
// divides maximum array elements
#include <bits/stdc++.h>
using namespace std;
#define MAXN 100001
// stores smallest prime factor for every number
int spf[MAXN];
// Calculating SPF (Smallest Prime Factor) for every
// number till MAXN.
// Time Complexity : O(nloglogn)
void sieve()
{
spf[1] = 1;
for (int i = 2; i < MAXN; i++)
// marking smallest prime factor for every
// number to be itself.
spf[i] = i;
// separately marking spf for every even
// number as 2
for (int i = 4; i < MAXN; i += 2)
spf[i] = 2;
for (int i = 3; i * i < MAXN; i++) {
// checking if i is prime
if (spf[i] == i) {
// marking SPF for all numbers divisible by i
for (int j = i * i; j < MAXN; j += i)
// marking spf[j] if it is not
// previously marked
if (spf[j] == j)
spf[j] = i;
}
}
}
// A O(log n) function returning primefactorization
// by dividing by smallest prime factor at every step
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;
}
// Function to find a number that
// divides maximum array elements
int maxElement(int A[], int n)
{
// precalculating Smallest Prime Factor
sieve();
// Hash to store frequency of each divisors
map<int, int> m;
// Traverse the array and get spf of each element
for (int i = 0; i < n; ++i) {
// calling getFactorization function
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;
}
// Driver program
int main()
{
int A[] = { 2, 5, 10 };
int n = sizeof(A) / sizeof(A[0]);
cout << maxElement(A, n);
return 0;
}
Java
// Java program to find a number that
// divides maximum array elements
import java.util.*;
class Solution
{
static final int MAXN=100001;
// stores smallest prime factor for every number
static int spf[]= new int[MAXN];
// Calculating SPF (Smallest Prime Factor) for every
// number till MAXN.
// Time Complexity : O(nloglogn)
static void sieve()
{
spf[1] = 1;
for (int i = 2; i < MAXN; i++)
// marking smallest prime factor for every
// number to be itself.
spf[i] = i;
// separately marking spf for every even
// number as 2
for (int i = 4; i < MAXN; i += 2)
spf[i] = 2;
for (int i = 3; i * i < MAXN; i++) {
// checking if i is prime
if (spf[i] == i) {
// marking SPF for all numbers divisible by i
for (int j = i * i; j < MAXN; j += i)
// marking spf[j] if it is not
// previously marked
if (spf[j] == j)
spf[j] = i;
}
}
}
// A O(log n) function returning primefactorization
// by dividing by smallest prime factor at every step
static Vector<Integer> getFactorization(int x)
{
Vector<Integer> ret= new Vector<Integer>();
while (x != 1) {
int temp = spf[x];
ret.add(temp);
while (x % temp == 0)
x = x / temp;
}
return ret;
}
// Function to find a number that
// divides maximum array elements
static int maxElement(int A[], int n)
{
// precalculating Smallest Prime Factor
sieve();
// Hash to store frequency of each divisors
Map<Integer, Integer> m= new HashMap<Integer, Integer>();
// Traverse the array and get spf of each element
for (int j = 0; j < n; ++j) {
// calling getFactorization function
Vector<Integer> p = getFactorization(A[j]);
for (int i = 0; i < p.size(); i++)
m.put(p.get(i),m.get(p.get(i))==null?0:m.get(p.get(i))+1);
}
int cnt = 0, ans = 10000000;
// Returns Set view
Set< Map.Entry< Integer,Integer> > st = m.entrySet();
for (Map.Entry< Integer,Integer> me:st)
{
if (me.getValue() >= cnt) {
cnt = me.getValue();
if(ans > me.getKey())
ans = me.getKey() ;
else
ans = ans;
}
}
return ans;
}
// Driver program
public static void main(String args[])
{
int A[] = { 2, 5, 10 };
int n =A.length;
System.out.print(maxElement(A, n));
}
}
//contributed by Arnab Kundu
Python
# Python3 program to find a number that
# divides maximum array elements
import math as mt
MAXN = 100001
# stores smallest prime factor for
# every number
spf = [0 for i in range(MAXN)]
# Calculating SPF (Smallest Prime Factor)
# for every number till MAXN.
# Time Complexity : O(nloglogn)
def sieve():
spf[1] = 1
for i in range(2, MAXN):
# marking smallest prime factor for
# every number to be itself.
spf[i] = i
# separately marking spf for every
# even number as 2
for i in range(4, MAXN, 2):
spf[i] = 2
for i in range(3, mt.ceil(mt.sqrt(MAXN + 1))):
# checking if i is prime
if (spf[i] == i):
# marking SPF for all numbers divisible by i
for j in range(2 * i, MAXN, i):
# marking spf[j] if it is not
# previously marked
if (spf[j] == j):
spf[j] = i
# A O(log n) function returning primefactorization
# by dividing by smallest prime factor at every step
def getFactorization (x):
ret = list()
while (x != 1):
temp = spf[x]
ret.append(temp)
while (x % temp == 0):
x = x //temp
return ret
# Function to find a number that
# divides maximum array elements
def maxElement (A, n):
# precalculating Smallest Prime Factor
sieve()
# Hash to store frequency of each divisors
m = dict()
# Traverse the array and get spf of each element
for i in range(n):
# calling getFactorization function
p = getFactorization(A[i])
for i in range(len(p)):
if p[i] in m.keys():
m[p[i]] += 1
else:
m[p[i]] = 1
cnt = 0
ans = 10**9+7
for i in m:
if (m[i] >= cnt):
cnt = m[i]
if ans > i:
ans = i
else:
ans = ans
return ans
# Driver Code
A = [2, 5, 10 ]
n = len(A)
print(maxElement(A, n))
# This code is contributed by Mohit kumar 29
C#
// C# program to find a number that
// divides maximum array elements
using System;
using System.Collections.Generic;
class Solution
{
static readonly int MAXN = 100001;
// stores smallest prime factor for every number
static int []spf = new int[MAXN];
// Calculating SPF (Smallest Prime Factor) for every
// number till MAXN.
// Time Complexity : O(nloglogn)
static void sieve()
{
spf[1] = 1;
for (int i = 2; i < MAXN; i++)
// marking smallest prime factor for every
// number to be itself.
spf[i] = i;
// separately marking spf for every even
// number as 2
for (int i = 4; i < MAXN; i += 2)
spf[i] = 2;
for (int i = 3; i * i < MAXN; i++)
{
// checking if i is prime
if (spf[i] == i)
{
// marking SPF for all numbers divisible by i
for (int j = i * i; j < MAXN; j += i)
// marking spf[j] if it is not
// previously marked
if (spf[j] == j)
spf[j] = i;
}
}
}
// A O(log n) function returning primefactorization
// by dividing by smallest prime factor at every step
static List<int> getFactorization(int x)
{
List<int> ret= new List<int>();
while (x != 1)
{
int temp = spf[x];
ret.Add(temp);
while (x % temp == 0)
x = x / temp;
}
return ret;
}
// Function to find a number that
// divides maximum array elements
static int maxElement(int []A, int n)
{
// precalculating Smallest Prime Factor
sieve();
// Hash to store frequency of each divisors
Dictionary<int, int> m= new Dictionary<int, int>();
// Traverse the array and get spf of each element
for (int j = 0; j < n; ++j)
{
// calling getFactorization function
List<int> p = getFactorization(A[j]);
for (int i = 0; i < p.Count; i++)
if(m.ContainsKey(p[i]))
m[p[i]] = m[p[i]] + 1;
else
m.Add(p[i], 1);
}
int cnt = 0, ans = 10000000;
// Returns Set view
foreach(KeyValuePair<int, int> me in m)
{
if (me.Value >= cnt)
{
cnt = me.Value;
if(ans > me.Key)
ans = me.Key ;
else
ans = ans;
}
}
return ans;
}
// Driver program
public static void Main(String []args)
{
int []A = { 2, 5, 10 };
int n =A.Length;
Console.Write(maxElement(A, n));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// JavaScript program to find a number that
// divides maximum array elements
let MAXN=100001;
// stores smallest prime factor for every number
let spf= new Array(MAXN);
for(let i=0;i<MAXN;i++)
{
spf[i]=0;
}
// Calculating SPF (Smallest Prime Factor) for every
// number till MAXN.
// Time Complexity : O(nloglogn)
function sieve()
{
spf[1] = 1;
for (let i = 2; i < MAXN; i++)
// marking smallest prime factor for every
// number to be itself.
spf[i] = i;
// separately marking spf for every even
// number as 2
for (let i = 4; i < MAXN; i += 2)
spf[i] = 2;
for (let i = 3; i * i < MAXN; i++) {
// checking if i is prime
if (spf[i] == i) {
// marking SPF for all numbers divisible by i
for (let j = i * i; j < MAXN; j += i)
// marking spf[j] if it is not
// previously marked
if (spf[j] == j)
spf[j] = i;
}
}
}
// A O(log n) function returning primefactorization
// by dividing by smallest prime factor at every step
function getFactorization(x)
{
let ret= [];
while (x != 1) {
let temp = spf[x];
ret.push(temp);
while (x % temp == 0)
x = Math.floor(x / temp);
}
return ret;
}
// Function to find a number that
// divides maximum array elements
function maxElement(A,n)
{
// precalculating Smallest Prime Factor
sieve();
// Hash to store frequency of each divisors
let m= new Map();
// Traverse the array and get spf of each element
for (let j = 0; j < n; ++j) {
// calling getFactorization function
let p = getFactorization(A[j]);
for (let i = 0; i < p.length; i++)
m.set(p[i],m.get(p[i])==null?0:m.get(p[i])+1);
}
let cnt = 0, ans = 10000000;
// Returns Set view
for (let [key, value] of m.entries())
{
if (value >= cnt) {
cnt = value;
if(ans > key)
ans = key ;
else
ans = ans;
}
}
return ans;
}
// Driver program
let A=[ 2, 5, 10];
let n =A.length;
document.write(maxElement(A, n));
// This code is contributed by patel2127
</script>
Time Complexity:O(N*log(N))
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem