Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get the numbers which can divide all values in an array - JavaScript
We are required to write a JavaScript function that takes in an array of numbers and returns a number which can exactly divide all the numbers in the array.
Let's say the following is our array:
const arr = [4, 6, 34, 76, 78, 44, 34, 26, 88, 76, 42];
Understanding the Problem
We need to find the common divisors that can divide all numbers in the array. This is essentially finding the Greatest Common Divisor (GCD) of all array elements and then finding all its divisors.
Method 1: Finding All Common Divisors
This approach finds all divisors of each number, then returns the common ones:
const arr = [4, 6, 34, 76, 78, 44, 34, 26, 88, 76, 42];
const dividesAll = el => {
const result = [];
let num;
for (num = Math.floor(el / 2); num > 1; num--){
if (el % num === 0) {
result.push(num);
}
};
return result;
};
const dividesArray = arr => {
return arr.map(dividesAll).reduce((acc, val) => {
return acc.filter(el => val.includes(el));
});
};
console.log(dividesArray(arr));
[ 2 ]
Method 2: Using GCD Approach (More Efficient)
A more efficient approach is to find the GCD of all numbers first, then find its divisors:
const arr = [4, 6, 34, 76, 78, 44, 34, 26, 88, 76, 42];
// Function to find GCD of two numbers
const gcd = (a, b) => {
while (b !== 0) {
let temp = b;
b = a % b;
a = temp;
}
return a;
};
// Function to find GCD of array
const arrayGCD = arr => {
return arr.reduce((result, current) => gcd(result, current));
};
// Function to find all divisors of a number
const findDivisors = num => {
const divisors = [];
for (let i = 1; i
GCD of array: 2
All common divisors: [ 1, 2 ]
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Direct Common Divisors | O(n × m) | O(n × d) | Medium |
| GCD-based Approach | O(n × log(min)) | O(d) | High |
Key Points
- The first method finds divisors for each number and filters common ones
- The GCD approach is more efficient for large arrays
- Both methods exclude 1 as a trivial divisor in the first approach
- The result [2] means 2 is the only non-trivial common divisor
Conclusion
The GCD-based approach is more efficient and mathematically sound. It first finds the greatest common divisor of all array elements, then finds all divisors of that GCD, giving us all numbers that can divide every element in the array.
