Logo

Programming-Idioms

  • Ruby
  • D
  • Js

Idiom #32 Integer exponentiation by squaring

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

function exp(x, n) {
   if (n===0) return 1;
   if (n===1) return x;
   return n%2 ? x * exp(x*x, (n-1)/2)
              : exp(x*x, n/2);
}
const exp = Math.pow;
def exp(x, n)
  x ** n
end
def exp(x, n)
  return 1 if n == 0
  return x if n == 1
  return exp(x*x, n/2) if n.even?
  x * exp(x*x, (n-1)/2)
end
uint exp(uint x, uint n) {
    if(n == 0)
        return 1;
    if(n == 1)
        return x;
    if(n % 2 == 0)
        return exp(x * x, n / 2);
    else
        return x * exp(x * x, (n - 1) / 2);
}
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...