Reputation: 8357
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;
}
}
Upvotes: 0
Views: 1345
Reputation: 6468
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
Upvotes: 9
Reputation: 3199
It basically works the same way log N time m power n algorithm works. Just trace the code for these two sets of input:
P.S:ans should be set to 1.
I am sure you will get it.
Upvotes: 1