的我實現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));
'的console.log(N)',你會看到問題 – Andreas
@Anthony:希望能找到它有用嗎? http://stackoverflow.com/a/38666376/747579 –
您的遞歸調用不在尾部位置。這裏是一個尾遞歸ES2015解決方案:'const power =(base,exp,acc = 1)=> exp === 0? acc:power(base,exp - 1,base * acc)'。 – ftor