Speeding up integer division if only certain bits in result are needed

74 Views Asked by At

Let's say I need to divide two integers $x$ and $y$, but I only care about the lowest 8 bits of the answer, i.e. I'm calculating:

$$r = \frac{x}{y}\,\,\%\,\,256$$where % is the modulus operator.

Is there a way to short-cut the answer rather than having to do the full division-calculation?

Update:

I'm entirely working with integer variables on a computer, so the result is rounded down to an integer as well. So, for example for $x=18423$ and $y=29$: $$r=\frac{18423}{29}\,\,\%\,\,256=635\,\,\%\,\,256=123$$

1

There are 1 best solutions below

6
On

If you know that $x$ can be divided by $y$ without remainder (i.e. $x/y=d \in N$ because, e.g., $y$ is the result of some gcd computation of $x$ with some other number) you can do the following (for simplicity let me further restrict the answer to $x,y>0$:

  1. $y = 2^k*y_1$ with $y_1$ odd. Hence $x$ must be divisible by $2^k$ and $x_1 = x/2^k$. $x/y$ = $x_1/y_1$.

  2. Since $y_1$ is odd there exists $z$ in $[0,255]$ with $z*y_1 \equiv 1 (256)$. Also there exists $x_2$ in $[0,255]$ with $x_1 \equiv x_2 (256)$. Now $d = x/y = x_1/y_1 \equiv x_2*z (256)$.