Created
January 20, 2015 22:01
-
-
Save goldsborough/9fc7c6cf86b5562ff502 to your computer and use it in GitHub Desktop.
Square-and-multiply algorithm for efficient exponentiation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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