Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript implementation of Math.pow

Tags:

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));
like image 955
Anthony Chung Avatar asked Jul 29 '16 19:07

Anthony Chung


1 Answers

Brief :

use parseInt or Math.floor to have y/2 as integer, unleness you will not reach 0 which is the stopper of recursion .


Details

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

}

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))
like image 89
Abdennour TOUMI Avatar answered Sep 28 '22 02:09

Abdennour TOUMI