Recursive Greatest Common Divisor

JavaScriptJavaScriptBeginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("JavaScript")) -.-> javascript/BasicConceptsGroup(["Basic Concepts"]) javascript(("JavaScript")) -.-> javascript/AdvancedConceptsGroup(["Advanced Concepts"]) javascript/BasicConceptsGroup -.-> javascript/variables("Variables") javascript/BasicConceptsGroup -.-> javascript/data_types("Data Types") javascript/BasicConceptsGroup -.-> javascript/arith_ops("Arithmetic Operators") javascript/BasicConceptsGroup -.-> javascript/comp_ops("Comparison Operators") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("Higher-Order Functions") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("Spread and Rest Operators") subgraph Lab Skills javascript/variables -.-> lab-28344{{"Recursive Greatest Common Divisor"}} javascript/data_types -.-> lab-28344{{"Recursive Greatest Common Divisor"}} javascript/arith_ops -.-> lab-28344{{"Recursive Greatest Common Divisor"}} javascript/comp_ops -.-> lab-28344{{"Recursive Greatest Common Divisor"}} javascript/higher_funcs -.-> lab-28344{{"Recursive Greatest Common Divisor"}} javascript/spread_rest -.-> lab-28344{{"Recursive Greatest Common Divisor"}} end

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.