![]() |
VOOZH | about |
Given two numbers n and d where d is a power of 2 number, the task is to perform n modulo d without the division and modulo operators.
Input: 6 4
Output: 2
Explanation: As 6%4 = 2
Input: 12 8
Output: 4
Explanation: As 12%8 = 4
Input: 10 2
Output: 0
Explanation: As 10%2 = 0
Approach:
The idea is to leverage bit manipulation for modulo operations when the divisor is a power of 2. Since any power of 2 has exactly one bit set, subtracting 1 from it gives a number with all bits to the right of that bit set. This creates a bit mask that, when combined with the bitwise AND operation, effectively performs the modulo operation without division.
This approach works because when we perform n % d where d is 2^k, we're essentially extracting the k least significant bits of n. For example, n % 4 is equivalent to getting the last 2 bits of n. When we calculate (d-1), we get a number with exactly k bits set to 1. Using the bitwise AND operation (n & (d-1)), we mask out all but the last k bits of n, which is exactly what n % d does when d is 2^k.
2
Time Complexity: O(1), As we are doing single operation which takes constant time.
Auxiliary Space: O(1), As constant extra space is used.