Search
Implement Power Function InterviewBit Solution
Updated: Sep 11, 2020
Problem: Implement Power Function
Problem Description:
Implement pow(x, n) % d.
Note that remainders on division cannot be negative. In other words, make sure the answer you return is non-negative.
For Example
Input : x = 2, n = 3, d = 3
Output : 2
2^3 % 3 = 8 % 3 = 2.Approach
The approach is pretty simple and straight forward.
Reduce y by half till it becomes 0, and each time square the x.
Whenever y is odd multiply x with the result, otherwise not.
Time & Space Complexity
Time complexity: O(logN), here N is ySpace complexity: O(1)Solution:
Code in C++



While I was on https://gamstopfreecasino.com, I had a moment about this post because the negative remainder issue is exactly what used to trip me up in coding tests. I've always solved pow(x,n) by brute force, so seeing the halving-and-squaring approach in O(log n) made me realize how unnecessary my long loops were. The way you handle the final adjustment to keep the answer non-negative is a practical trick I'll remember.