top of page

Looking to master object-oriented and system design for tech interviews or career growth?

  • Improve your system design and machine coding skills.

  • Study with our helpful resources.

  • Prepare for technical interviews and advance your career.

**We're in beta mode and would love to hear your feedback.

Implement Power Function InterviewBit Solution

Sep 6, 2020
1 min read

Updated: Sep 11, 2020


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 y
Space complexity: O(1)


Solution:


Code in C++


1 Comment


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.

Like
bottom of page