javascript
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.
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.
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.
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) {
}
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);
}
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);
}
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);
}
Find the largest number that divides two or more numbers without leaving a remainder
Learn moreThe 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