Skip to content

Instantly share code, notes, and snippets.

@goldsborough
Created January 20, 2015 22:01
Show Gist options
  • Save goldsborough/9fc7c6cf86b5562ff502 to your computer and use it in GitHub Desktop.
Save goldsborough/9fc7c6cf86b5562ff502 to your computer and use it in GitHub Desktop.
Square-and-multiply algorithm for efficient exponentiation
long squareAndMultiply(long base, unsigned short power)
{
// x^0 = 1
if (! power) return 1;
// x^1 = x
if (power == 1) return base;
// if power is odd
if (power % 2)
{
// Make the power an even number by moving
// one multiplication out of the power and
// in front of the equation, then call the
// the function recursively, reducing x^n
// to (x^2)^n/2, since succesive powers are
// multiplied in a mathematical equation
return base * squareAndMultiply(base*base,(power-1)/2);
}
// else if power is even, do same as
// for odd but without the need to make
// it even anymore
else return squareAndMultiply(base*base,power/2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment