Embedding JavaScript in Math.pow

I implemented Math.pow using the log (n) solution, just like this article on geeksforgeeks

http://www.geeksforgeeks.org/write-ac-program-to-calculate-powxn/

However, I found that the function does not exit the base code, as I expected. This program seems to work in C, but not JS.

So I conclude that there is something about C that I accept in JavaScript too.

What am I missing in my JavaScript implementation?

Be warned: the code, as it will exceed the maximum call stack

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));
Run codeHide result
+4
source share
2 answers

Short description:

parseInt Math.floor, y/2 , , 0, .


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);

}

[JS Algo] :

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))
     }

}

DEMO:

    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))
Hide result
+1

@Abdennour

function power(x, y) {
    if (y === 0) {
      return 1;
    }
    var yBy2 = y / 2;
    var pow = power(x, parseInt( yBy2, 10) );
    if (y % 2 === 0) {
      return pow * pow;
    } else {
      return x * pow * pow;
    }
}
Hide result
0

Source: https://habr.com/ru/post/1649576/


All Articles