C++ implementation of the square-and-multiply algorithm