Simplification of nested module operations.

455 Views Asked by At

Can I simplify this formula to use only one module operation?

$$(x + (y \text{ mod } z)) \text{ mod }z$$

Intuitively I simplified it so:

$$(x + y) \text{ mod } z$$

This seems to do the same as the original. However, I don't know why it works nor if this is right.

5

There are 5 best solutions below

1
On BEST ANSWER

Mathematically, this is correct. Let $y$ = $mz+y'$, with $0 {\le}y'{\lt}z$. Then $x+y$ = $x+y'+mz$, so $x+y$ and $x+y'$ clearly have the same remainder modulo $z$.

However, if you are performing this calculation on a computer, beware: If $x$ and $y$ are of integer type (signed or unsigned), it is possible that adding $x$ to $y$ overflows while adding $x$ to $y'$ does not, which may impact the result.

0
On

You are indeed right. Define $x, y$:
$x,y=nz+a$, for $0\leq a<z$ Plug in the original equation: $$(n_xz+a_x)+(n_yz+a_y)\mod{z}$$ Add both terms: $$n_{sum}z+a_x+a_y\mod{z}$$ First term cancels: $$a_x+a_y\mod{z}$$ The same obviously happens if we cancel $n_yz$ first: $$(n_xz+a_x)+(n_yz+a_y\mod{z})\mod{z}$$ $$=n_xz+a_x+a_y\mod{z}$$ $$=a_x+a_y\mod{z}$$

0
On

Yes it works.

(x + (y % z)) % z

= x % z + y % z % z .......(1)

Taking modulo twice or once of any number don't makes change.

So y % z % z = y % z

From (1),

= x % z + y % z

= (x + y) % z

1
On

The way you are writing this, it looks like you are actually talking about the operator % in some c-like programming language. In that case, be warned that if negative numbers are involved, the % operator can yield negative results (see https://en.wikipedia.org/wiki/Modulo_operation for details). With negative results, the two terms can produce different values that are the same mod z.

For example, my Visual Studio for C# says

$(3 + (-5 \% 3)) \% 3 = 1$, but $ (3 + (-5)) \% 3 = -2$.

Of course $1 \equiv -2 \pmod 3$, but if you compare values in your program, then they will compare as different.

0
On

$$(x + (y \text{ mod } z)) \text{ mod }z = $$ $(y \text{ mod } z) \implies y=qz + r \implies r = y - qz = (y \text{ mod } z)$ $$(x + (y - qz)) \text{ mod }z =$$ $$ (x + y - qz) \text{ mod }z =$$ $(x + y - qz) \text{ mod }z \implies (x + y - qz) = nz + p \implies p= (x + y - qz)-nz $ $$ (x + y - qz)-nz=$$ $$ x + y - (q -n)z =$$ $(q -n) = m$ $$ x + y + mz$$