JavaScript

Write a Javascript Program to Compute the Greatest Common Divisor GCD of Two Positive Integers

In this tutorial, we are going to see how to write a javascript program to compute the greatest common divisor GCD of two positive integers. The GCD or the Greatest Common Divisor of two integers which is the largest integer that can divide the two numbers exactly (without remainder). Example:
 


 
 

Script to calculate the GCD iteratively
function pgcd(a,b) {
    a = Math.abs(a);
    b = Math.abs(b);
    if (b > a) {
       var tmp = a; 
       a = b; 
       b = tmp;
    }
    while (true) {
        if (b == 0) return a;
        a %= b;
        if (a == 0) return b;
        b %= a;
    }
}

console.log(pgcd(60,36));

Output:

12
 

Script to calculate the GCD recursively
function pgcd(a, b) {
    if (b) {
        return pgcd(b, a % b);
    } else {
        return Math.abs(a);
    }
}

console.log(pgcd(60,36));

Output:

12
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *