Compute n modulo d without division(/) and modulo(%) operators, where d is a power of 2 number.
Let ith bit from right is set in d. For getting n modulus d, we just need to return 0 to i-1 (from right) bits of n as they are and other bits as 0.
For example if n = 6 (00..110) and d = 4(00..100). Last set bit in d is at position 3 (from right side). So we need to return last two bits of n as they are and other bits as 0, i.e., 00..010.
Now doing it is so easy, guess it….
Yes, you have guessing it right. See the below program.
Please write comments if you find any bug in the above program/algorithm or other ways to solve the same problem.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Optimization Techniques | Set 1 (Modulus)
- Check a number is odd or even without modulus operator
- Compute the parity of a number using XOR and table look-up
- Compute the integer absolute value (abs) without branching
- Compute the minimum or maximum of two integers without branching
- Calculate 7n/8 without using division and multiplication operators
- Fast average of two numbers without division
- Divide two integers without using multiplication, division and mod operator
- Cyclic Redundancy Check and Modulo-2 Division
- Find a Mother vertex in a Graph using Bit Masking
- XOR of elements in a given range with updates using Fenwick Tree
- Query to count odd and even parity elements in subarray after XOR with K
- Maximum weighted edge in path between two nodes in an N-ary tree using binary lifting
- Split a binary string into K subsets minimizing sum of products of occurrences of 0 and 1
Improved By : vt_m