w3resource

JavaScript: Find the Greatest Common Divisor or GCD of more than 2 integers

JavaScript Math: Exercise-9 with Solution

Write a JavaScript function to find the GCD (greatest common divisor) of more than 2 integers.

Test Data:
console.log(gcd_more_than_two_numbers([3,15,27]));
console.log(gcd_more_than_two_numbers([5,10,15,25]));
Output :
3
5

Sample Solution:-

HTML Code:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>GCD (greatest common divisor) of more than 2 integers</title>
</head>
<body>
</body>
</html>

JavaScript Code:

function gcd_more_than_two_numbers(input) {
  if (toString.call(input) !== "[object Array]")  
        return  false;  
  var len, a, b;
	len = input.length;
	if ( !len ) {
		return null;
	}
	a = input[ 0 ];
	for ( var i = 1; i < len; i++ ) {
		b = input[ i ];
		a = gcd_two_numbers( a, b );
	}
	return a;
}

function gcd_two_numbers(x, y) {
  if ((typeof x !== 'number') || (typeof y !== 'number')) 
    return false;
  x = Math.abs(x);
  y = Math.abs(y);
  while(y) {
    var t = y;
    y = x % y;
    x = t;
  }
  return x;
}
console.log(gcd_more_than_two_numbers([3,15,27]));
console.log(gcd_more_than_two_numbers([5,10,15,25]));

Sample Output:

3
5

Flowchart:

Flowchart: JavaScript Math- GCD (greatest common divisor) of more than 2 integers

Live Demo:

See the Pen javascript-math-exercise-9 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript function to get the greatest common divisor (gcd) of two integers.
Next: Write a JavaScript function to get the least common multiple (LCM) of two numbers.

What is the difficulty level of this exercise?



JavaScript: Tips of the Day

Promise.all method

const promise1 = Promise.resolve('First')
const promise2 = Promise.resolve('Second')
const promise3 = Promise.reject('Third')
const promise4 = Promise.resolve('Fourth')

const runPromises = async () => {
	const res1 = await Promise.all([promise1, promise2])
	const res2  = await Promise.all([promise3, promise4])
	return [res1, res2]
}

runPromises()
	.then(res => console.log(res))
	.catch(err => console.log(err))

The Promise.all method runs the passed promises in parallel. If one promise fails, the Promise.all method rejects with the value of the rejected promise. In this case, promise3 rejected with the value "Third". We're catching the rejected value in the chained catch method on the runPromises invocation to catch any errors within the runPromises function. Only "Third" gets logged, since promise3 rejected with this value.