Logo

Programming-Idioms

  • Ada
  • Smalltalk

Idiom #32 Integer exponentiation by squaring

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

exp: n
	n = 0 ifTrue: [^ 1].
	n = 1 ifTrue: [^ self].
	n%2 = 0 ifTrue: [^ self * self exp: n/2].
	^ self * (self * self exp: n-1/2)

This would be a method of Integer. Integers unlimited
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...