Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitshifts to obtain remainder

I want to know how to obtain the remainder by dividing an integer with another integer (both positive) using bitshift or bitwise operators only. The / operator or % operator should not be used.

For example, for obtaining the remainder when divisor is of the form 2^k the following operation yields the remainder.

m = Remainder

n = The number

d = The divisor

m = n & ( d - 1 )

However this method works only when d is of the form 2^k . I want to know a similar method for non-powers of 2. I am currently working on a problem from programming challenges and want to employ such a method to reduce program execution time

like image 731
Extreme Coders Avatar asked Nov 25 '12 04:11

Extreme Coders


People also ask

How do I find bitwise remainder?

int n = ..; int z = ..; int quotient = n >> z; int remainder = n & ~((~(int)0) << z); Likewise, in the more general case, integer division ( / ) is paired with the modulo operator ( % ). Each operator only returns one value.

What is the output of left shift operator << on 00011000 << 2?

What is the output of left shift operator << on 00011000 << 2? If both operands are different, output is 1.

How do you calculate Left Shift and Right Shift?

@Jani A left shift corresponds by a division by 2. A right shift corresponds to multiplication my 2. This is often handy to keep in mind when doing bit shifting.


1 Answers

Any answer that doesn't use the operator % will be a less efficient answer, but, if you absolutely cannot use the operator, then, one solution is to use a loop to subtract d from n repeatedly:

m = n;
while (m >= d)
{
  m -= d;
}

Assuming that your integers are 32-bit, then you can consider an optimized version where we delete multiples of d from n:

m = n;
for (i = 31; i >= 0; i--)
{
  di = d << i;
  if (di > 0 && m >= di) m -= di;
}

This example, assumes the integers are signed and watches for overflow i.e. the test for di > 0.

like image 62
Stephen Quan Avatar answered Sep 29 '22 06:09

Stephen Quan