I am working on finding the greatest common divider of two numbers. I have algorithm as following:
function gcd(a,b){
var temp = a;
if(b > a){
a = b;
b = temp;
}
var remainder = a % b;
console.log("remainder: "+ remainder);
while(remainder){
a = b;
b = remainder;
gcd(a,b);
}
return b;
}
Inside the while loop,directing calling the gcd(a,b) causes the program to crash:
while(remainder){
a = b;
b = remainder;
gcd(a,b);
}
but returning gcd(a,b) instead of calling it works:
while(remainder){
a = b;
b = remainder;
return gcd(a,b);
}
I don't understand the differences. Why doesn't the first case stops when it reaches base case as remainder -> 0 ?