I implemented Math.pow using a log(n) solution just like this article on geeksforgeeks
http://www.geeksforgeeks.org/write-a-c-program-to-calculate-powxn/
However, I'm finding that the function does not exit its base case as I had intended. This program seems like it works in C but not JS.
Therefore, I am concluding that there is something about C that I am assuming works as well in JavaScript.
What am I missing in my JavaScript implementation?
Be forewarned: the codesnippet as it is will have a max call stack exceeded error
var myPow = function(x, n) {
var res = 1
var temp;
if (n === 0) {
return 1;
}
temp = myPow(x, n / 2)
if (n % 2 === 0) {
return temp * temp
} else {
return x * temp * temp
}
};
console.log(myPow(2,3));
use parseInt
or Math.floor
to have y/2
as integer, unleness you will not reach 0
which is the stopper of recursion .
if you want to transalte [C Algo]:
int power(int x, unsigned int y)
{
if( y == 0)
return 1;
else if (y%2 == 0)
return power(x, y/2)*power(x, y/2);
else
return x*power(x, y/2)*power(x, y/2);
}
To [JS Algo] , you will have :
function power(x,y){
if(y===0){return 1}
else if (y%2 ===0){
return power(x,parseInt(y/2))*power(x,parseInt(y/2))
}else{
return x*power(x,parseInt(y/2))*power(x,parseInt(y/2))
}
}
function power(x,y){
if(y===0){return 1}
else if (y%2 ===0){
return power(x,parseInt(y/2))*power(x,parseInt(y/2))
}else{
return x*power(x,parseInt(y/2))*power(x,parseInt(y/2))
}
}
console.log(power(3,2))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With