We know that for various reasons, there is no standard integer power function in C++. I’m performing exact arithmetic with rather small integers, what is the correct way to compute powers?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The standard, fast exponentiation uses repeated squaring:
The number of steps is logarithmic in the value of
exponent. This algorithm can trivially be extended to modular exponentiation.Update: Here is a modified version of the algorithm that performs one less multiplication and handles a few trivial cases more efficiently. Moreover, if you know that the exponent is never zero and the base never zero or one, you could even remove the initial checks: