Introduction
In this lab, we will be exploring the concept of finding the greatest common divisor between two or more numbers/arrays using JavaScript. The lab will introduce a function that uses recursion to calculate the GCD, with a base case of zero. By the end of the lab, you will have a solid understanding of how to implement this function in your own JavaScript projects.
How to Calculate the Greatest Common Divisor
To calculate the greatest common divisor between two or more numbers/arrays using code, follow these steps:
Open the Terminal/SSH and type
nodeto start practicing coding.Use the following code:
const gcd = (...arr) => {
const _gcd = (x, y) => (!y ? x : gcd(y, x % y));
return [...arr].reduce((a, b) => _gcd(a, b));
};
The
gcdfunction uses recursion.The base case is when
yequals0. In this case, the function returnsx.Otherwise, the function returns the GCD of
yand the remainder of the divisionx / y.To test the function, use the following code:
gcd(8, 36); // 4
gcd(...[12, 8, 32]); // 4
Summary
Congratulations! You have completed the Greatest Common Divisor lab. You can practice more labs in LabEx to improve your skills.