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.
- Next higher number with same number of set bits
- Add 1 to a given number
- Multiply a given Integer with 3.5
- Turn off the rightmost set bit
- Find whether a given number is a power of 4 or not
- Compute the integer absolute value (abs) without branching
- Compute the minimum or maximum of two integers without branching
- Rotate bits of a number
- Find the two non-repeating elements in an array of repeating elements
- Count set bits in an integer
- Write an Efficient C Program to Reverse Bits of a Number
- Little and Big Endian Mystery
- Check for Integer Overflow
- Find the Number Occurring Odd Number of Times
- Program to find whether a no is power of two
Improved By : vt_m