Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Dart

Idiom #32 Integer exponentiation by squaring

Create function exp which calculates (fast) the value x power n.
x and n are non-negative integers.

int exp(int x, int n) {
  var r = 1;
  while (true) {
    if (n.isOdd) r *= x;
    n ~/= 2;
    if (n == 0) break;
    x *= x;
  }
  return r;
}

The idiomatic way to do exponentiation by squaring is a loop, not a recursive function.

This one puts the break before the x*=x to avoid an extra unnecessary multiplication at the end.
int exp(int x, int n) {
  if (n == 0) return 1;
  if (n == 1) return x;
  var r = exp(x * x, n ~/ 2);
  if (n % 2 == 1) r *= x;
  return r;
}
unsigned int exp(unsigned int x,unsigned int n)
{
    if(n==0)
    {
        return 1;
    }
    if(n==1)
    {
        return x;
    }
    if(!(n%2))
    {
        return exp(x*x,n/2);
    }
    return x*exp(x*x,(n-1)/2);
}

New implementation...