How to find GCD/HCF of 2 numbers ?

Saurabh Staff asked 1 year ago

Can someone help with an algorithm to print GCD of 2 numbers ?

1 Answers
Saurabh Staff answered 1 year ago

Here is a simple algorithm which divides the 2 numbers iteratively, swapping the remainder
with the smaller number until the remainder gets to 0 and then returns the larger number.


function gcd(i, j) {
     var r = -1;
 
     if (i < j) {
         var temp;
         temp = i;
         i = j;
         j = temp;
    }
 
    while (r) {
        r = i – parseInt(i/j) *j;
        i = j;
        j = r;
    }
 
    return i;
}