Logo

Programming-Idioms

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

Idiom #32 Integer exponentiation by squaring

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

def exp(x: Int, n: Int): Int {
  if(n == 0) {
    1
  } else if(n == 1) {
    x
  } else if(n%2 == 0) {
    exp(x*x, n/2)
  } else {
    x * exp(x*x, (n-1)/2)
  }
}

This isn't tail recursive because of the last else branch.
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...