How to use the Recursive method In Javascript

In this approach, the recursive function myFunction calculates GCD using the Euclidean algorithm. If b=0, returns a; otherwise, recursively calls with b and remainder of a/b.

Syntax:

function myFunction(a, b) {
if ( b === 0 ) {
return a;
}
return myFunction(b, a % b);
}

Example: In this example, we are using the above-explained approach.

Javascript




function myFunction(a, b) {
    if (b === 0) {
        return a;
    }
    return myFunction(b, a % b);
}
 
let num1 = 12;
let num2 = 18;
let result = myFunction(num1, num2);
console.log(`GCD of ${num1} and ${num2} is ${result}`);


Output

GCD of 12 and 18 is 6

JavaScript Program to Find GCD or HCF of Two Numbers

GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest positive integer that divides both numbers without leaving a remainder.

GCD ( a, b ) = [ |a.b| ] / [ lcm(a, b) ]
or,
HCF of factors = Product of the Numbers/ LCM of numbers

Example:

Input: a = 20, b = 28
Output: 4
Explanation: The factors of 20 are 1, 2, 4, 5, 10 and 20.
The factors of 28 are 1, 2, 4, 7, 14 and 28. Among these factors,
1, 2 and 4 are the common factors of both 20 and 28.
The greatest among the common factors is 4.

There are several methods that to Find GCD or HCF of Two Numbers in JavaScript, which are listed below:

Table of Content

  • Using for Loop
  • Using the Recursive method
  • Using if…else Statements

Similar Reads

Using for Loop

In this approach we are using a for loop to find GCD/HCF, iterating from 1 to the minimum of the two numbers. Update GCD when both numbers are divisible....

Using the Recursive method

...

Using if…else Statements

In this approach, the recursive function myFunction calculates GCD using the Euclidean algorithm. If b=0, returns a; otherwise, recursively calls with b and remainder of a/b....