admin管理员组

文章数量:1279189

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

/

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

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

http://www.geeksforgeeks/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));

Share Improve this question edited Jul 29, 2016 at 20:31 user6445533 asked Jul 29, 2016 at 19:35 Anthony ChungAnthony Chung 1,4772 gold badges25 silver badges46 bronze badges 4
  • 2 console.log(n) and you will see the problem – Andreas Commented Jul 29, 2016 at 19:39
  • @Anthony :hope to find it useful ? stackoverflow./a/38666376/747579 – Abdennour TOUMI Commented Jul 29, 2016 at 19:52
  • Your recursive call isn't in tail position. Here's a tail recursive ES2015 solution: const power = (base, exp, acc = 1) => exp === 0 ? acc : power(base, exp - 1, base * acc). – user6445533 Commented Jul 29, 2016 at 19:56
  • Take a look at iterative (non recursive) approaches on integer math for some additional ideas: Power by squaring for negative exponents – Spektre Commented Jul 30, 2016 at 6:45
Add a ment  | 

4 Answers 4

Reset to default 7

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

Try this out

It will give you the same result of JavaScript build in method ( Math.pi(x, y)) but the only problem is you can't use Power as decimal number.

Math.my_pow = (x, y) => {
  if (typeof x != "number" || typeof y != "number")
    throw "(x) and (y) should only be number";

  if (y == 0) return 1;
  if (x == 0 && y > 0 ) return 0;

  const base = x;
  var value = base;
  var pow = y;
  if (y < 0) pow = y * -1;

  for (var i = 1; i < pow; i++) {
    value *= base;
  }

  if (y < 0) return 1 / value;
  return value;
};

try {
  console.log( Math.my_pow(0, -3) );
  console.log( Math.pow(0, -2) );

  console.log( Math.my_pow(-5, -3) );
  console.log( Math.pow(-5, -3) );

  console.log( Math.my_pow(8, -7) );
  console.log( Math.pow(8, -7)) ;
} catch (err) {
  console.log(err);
}

Modifying a little bit from @Abdennour's answer

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

* Simple Logic *

function pow (p,y){
    if(p > 0 && y === 0){
        return 1;
    }
    x = p;
    while(y > 1){
        x = p*x;
        y--;
    }
    return x;
}


console.log(pow(0,0)+'\n'); // 0
console.log(pow(2,4)+'\n'); // 16
console.log(pow(2,0)+'\n'); // 1
console.log(pow(0,2)+'\n'); // 0

本文标签: algorithmJavaScript implementation of MathpowStack Overflow