how to apply bitmasking in this problem
How to apply bitmasking in this problem
Hello @pragyachoudhary1111,
APPROACH:
This method uses bitmasks and without using extra space to calculate a^n in O(log n) time.
- Let’s take variable ans in which we store the result and initialize it with 1.
- Extract last bit from n.
- If the Extracted bit is 1 multiply ans with a, otherwise if the Extracted bit is 0 then don’t multiply.
- Update a to a*a.
- Discard rightmost bit i.e right shift b by 1.
- Repeat steps 2 to 5 until n becomes 0.
Following is the program explaining this:
/* Iterative Function to calculate (x^y) in O(log y) */
int power(int x, unsigned int y)
{
int res = 1; // Initialize resultwhile (y > 0) { // If y is odd, multiply x with result if (y & 1) res = res*x; // y must be even now y = y>>1; // y = y/2 x = x*x; // Change x to x^2 } return res;
}
Hope, this would help.
Give a like, if you are satisfied.