Here’s the code that does the trick. I do know the concept how to calculate m^n in O(logn) time, and I think it’s related, but how?
for(long long int i = 2; N; N /= 2, i *= i){
if(N & 1){
ans *= i;
}
}
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.
That’s the square and multiply algorithm.
N /= 2 has the effect of removing the lowest bit (and when all the bits remaining are zero, the algorithm is finished).
N & 1 checks if the lowest bit is odd or even