long.js
long.js copied to clipboard
Feature request: power(exponent)
Fantastic library! I've ported it to Lua. https://github.com/BixData/lua-long
Anyone know how to implement a power function? It'd make a great addition.
What about something like this:
double MathPow_Double_Int(double x, int n) {
double ret;
if ((x == 1.0) || (n == 1)) {
ret = x;
} else if (n < 0) {
ret = 1.0 / MathPow_Double_Int(x, -n);
} else {
ret = 1.0;
while (n--) {
ret *= x;
}
}
return (ret);
}
As mentioned here?
Since I also needed this and maybe it helps someone, here is my little square-multiply implementation that should work for non-negative exponents:
function long_pow(a: long, b: long /*non-negative*/): long {
if (b.isZero()) return long.ONE;
if (a.eq(long.ONE) || b.eq(long.ONE)) return a;
while (b.isEven()) {
b = b.shru(1);
a = a.mul(a);
}
return long_pow(a, b.sub(1)).mul(a);
}
Let me know if I buggered it up!