javascript

findGCD()

Parameters: num1(number), num2(number)

num1 and num2 are the two numbers for which we are finding the GCD

Returns: The function returns a number, which is the greatest common divisor of num1 and num2

The findGCD function in Javascript allows a programmer to determine the greatest common divisor of two numbers.

functions
recursion
arithmetics
variables
Easy dificulty

Crafting a JavaScript Function to Find the Greatest Common Divisor (GCD)

Hello fellow programmer! Thanks for checking this post. Here we're going to explore a function named 'findGCD' in JavaScript. Finding the greatest common divisor (GCD) can be pretty routine, but if you're new to programming or just need a little refresher, this post is sure to facilitate your understanding. Strap in and prepare to dive into the logic behind this universal function.

Step 1: Define the Problem

In this step, we try to identify our problem. Our problem here is to find the Greatest Common Divisor (GCD) of two numbers. The GCD of two or more integers is the largest positive integer that divides each of the integers without a remainder.

Step 2: Start Coding Function

In JavaScript, we define our function findGCD that takes two parameters num1 and num2, which are the two numbers we're finding the GCD of.

function findGCD(num1, num2) {
}

Step 3: Implement Euclidean Algorithm

We could use the Euclidean algorithm to find the GCD. First, we check if num2 is zero. If true, num1 is our GCD. Otherwise, we recursively call findGCD with num2 and the remainder of num1 divided by num2 as the parameters.

function findGCD(num1, num2) {
  if(num2 === 0) return num1;
  return findGCD(num2, num1 % num2);
}

Step 4: Include Input Check

It's good practice to check the inputs. Here, we'll check if both inputs are numbers otherwise return a message stating that both inputs must be numbers.

function findGCD(num1, num2) {
  if(typeof num1 !== 'number' || typeof num2 !== 'number') return 'Both inputs must be numbers';
  if(num2 === 0) return num1;
  return findGCD(num2, num1 % num2);
}

Step 5: Full and Final Code

Now, we have our final function that first checks if inputs are numbers, then calculates the GCD using the Euclidean algorithm.

function findGCD(num1, num2) {
  if(typeof num1 !== 'number' || typeof num2 !== 'number') return 'Both inputs must be numbers';
  if(num2 === 0) return num1;
  return findGCD(num2, num1 % num2);
}

Learn function in:

Greatest Common Divisor (GCD)

Find the largest number that divides two or more numbers without leaving a remainder

Learn more

Mathematical principle

The function employs the Euclidean algorithm. The Euclidean algorithm is a method for computing the greatest common divisor of two numbers. It's based on the observation that the gcd of two numbers also divides their difference. The algorithm recursively reduces the problem of finding the gcd to smaller instances of the same problem until the gcd is found.

Learn more