Square-and-multiply algorithm