Whilst studying recursion, I attempted to get a C++ example function working in javascript.
The original function (from Stanford CS106B) is here:
int Raise (int base, int exp)
{
if (exp == 0)
return 1;
else
{
int half = Raise(base, exp/2);
if (exp % 2 === 0)
return half * half;
else
return base * half * half;
}
}
Raise(3,5);
My version below recurses far too many times. What fundamental thing have I messed up? I bet it's the line with var half... I've never tried to assign a function to a variable, so that's also new territory...
function Raise (base, expo)
{
if (expo === 0)
return 1;
else
{
var half = Raise(base, (expo/2));
if (expo % 2 === 0)
return half * half;
else
return base * half * half;
}
}
Raise(3,5);