long.js icon indicating copy to clipboard operation
long.js copied to clipboard

Feature request: power(exponent)

Open drauschenbach opened this issue 6 years ago • 2 comments

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.

drauschenbach avatar Dec 05 '17 01:12 drauschenbach

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?

drauschenbach avatar Dec 05 '17 01:12 drauschenbach

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!

olydis avatar May 30 '18 16:05 olydis