How to use subtraction algorithm In Javascript

This approach employs the subtraction algorithm, which repeatedly subtracts the smaller number from the larger one until both numbers become equal, finding the G.C.D of the original numbers. This method offers simplicity and effectiveness in G.C.D computation through recursion.

Example: In the base case, if a equals b, it means we have found the G.C.D. In the recursive cases, we subtract the smaller number from the larger one until both become equal.

Javascript




function gcdRecursiveSubtraction(a, b) {
    // Base case
    if (a === b) {
        return a;
    }
     
    // Recursive cases
    if (a > b) {
        return gcdRecursiveSubtraction(a - b, b);
    } else {
        return gcdRecursiveSubtraction(a, b - a);
    }
}
 
// Example usage
const num1 = 36;
const num2 = 48;
console.log(`G.C.D of ${num1} and ${num2} is: ${gcdRecursiveSubtraction(num1, num2)}`);


Output

G.C.D of 36 and 48 is: 12

JavaScript Program to Find G.C.D Using Recursion

The greatest common divisor (G.C.D) of two integers is the largest positive integer that divides both numbers without leaving a remainder. In JavaScript, finding the greatest common divisor (G.C.D) of two numbers using recursion is a common programming task. Recursion is a powerful technique where a function calls itself to solve smaller instances of the same problem until it reaches a base case.

Below are the approaches to finding the G.C.D using recursion in JavaScript:

Syntax:

function functionName(parameters) {
// Base case
if (condition) {
// Return value or perform action
} else {
// Recursive call
functionName(modifiedParameters);
// Additional computation (optional)
}
}

Similar Reads

Using recursion

Using the Euclidean algorithm, we define a recursive function to find the G.C.D of two numbers. The Euclidean algorithm is widely used for computing the greatest common divisor of two integers. It relies on the principle that the G.C.D of two numbers also divides their difference, which helps reduce the problem into simpler subproblems until a base case is reached. This approach offers a clear and concise solution leveraging the power of recursion in JavaScript....

Using subtraction algorithm

...

Using binary euclidean algorithm

This approach employs the subtraction algorithm, which repeatedly subtracts the smaller number from the larger one until both numbers become equal, finding the G.C.D of the original numbers. This method offers simplicity and effectiveness in G.C.D computation through recursion....

Contact Us