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
Selected Reading
Finding the smallest fitting number in 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. This is essentially finding the Greatest Common Divisor (GCD) of all numbers.
Therefore, let's write the code for this function ?
Example
The code for this will be ?
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));
Output
The output in the console will be ?
[ 2 ]
How It Works
The solution works in two steps:
-
Find all divisors: The
dividesAllfunction finds all divisors of each number (excluding 1 and the number itself) -
Find common divisors: The
dividesArrayfunction maps each number to its divisors, then reduces to find divisors common to all numbers
Alternative Approach: Using GCD
A more efficient approach uses the mathematical GCD algorithm:
const findGCD = (a, b) => {
while (b !== 0) {
let temp = b;
b = a % b;
a = temp;
}
return a;
};
const findArrayGCD = arr => {
return arr.reduce((gcd, num) => findGCD(gcd, num));
};
const arr2 = [12, 18, 24];
console.log("GCD of array:", findArrayGCD(arr2));
// For the original array
const originalArr = [4, 6, 34, 76, 78, 44, 34, 26, 88, 76, 42];
console.log("GCD of original array:", findArrayGCD(originalArr));
GCD of array: 6 GCD of original array: 2
Conclusion
Both approaches find the largest number that divides all array elements. The GCD algorithm is more efficient for large arrays, while the divisor-filtering approach shows all common divisors.
Advertisements
