Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: power(exponent) #46

Open
drauschenbach opened this issue Dec 5, 2017 · 2 comments
Open

Feature request: power(exponent) #46

drauschenbach opened this issue Dec 5, 2017 · 2 comments

Comments

@drauschenbach
Copy link

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 drauschenbach changed the title Feature request: power(n, exponent) Feature request: power(exponent) Dec 5, 2017
@drauschenbach
Copy link
Author

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?

@olydis
Copy link

olydis commented May 30, 2018

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants