Recursive Greatest Common Divisor

Beginner

This tutorial is from open-source community. Access the source code

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:

  1. Open the Terminal/SSH and type node to start practicing coding.

  2. 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));
};
  1. The gcd function uses recursion.

  2. The base case is when y equals 0. In this case, the function returns x.

  3. Otherwise, the function returns the GCD of y and the remainder of the division x / y.

  4. 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.