2016-07-29 62 views
4

的我實現Math.pow使用的log(n)的解決方案,就像這篇文章geeksforgeeksJavaScript實現Math.pow

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

然而,我發現,該功能不會退出其基地就像我原本打算的那樣。這個程序看起來像在C中工作,但不是JS。

因此,我得出結論,有一些關於C,我假設在JavaScript中的作品。

我的JavaScript實現中缺少什麼?

事先警告:,因爲它是將有一個最大調用堆棧超出誤差

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

+2

'的console.log(N)',你會看到問題 – Andreas

+0

@Anthony:希望能找到它有用嗎? http://stackoverflow.com/a/38666376/747579 –

+0

您的遞歸調用不在尾部位置。這裏是一個尾遞歸ES2015解決方案:'const power =(base,exp,acc = 1)=> exp === 0? acc:power(base,exp - 1,base * acc)'。 – ftor

回答

1

簡要的codesnippet:

使用parseIntMath.floory/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))

+0

雖然這通常是安全的,它是標準最佳實踐始終爲parseInt提供基數:'parseInt(y/2,10)' – rgthree

+3

'parseInt()'分析字符串並返回一個整數。你應該使用['Math.floor()'](https://developer.mozilla。org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor)而不是截斷小數點位置 – Andreas

+0

@Andreas&@rgthree:THank u,無論如何,想法是在遞歸結束避免'Infinity' –

0

修改從@ 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; 
 
    } 
 
}