1
$\begingroup$

In a programming algorithm, I'm using the result of k % y. I need to understand how to adjust k when the value of y is incremented by one to preserve the same modulo result.

In other words, solve for x: (k + x) % (y + 1) = k % y

Empirically, I see that I can always adjust k by adding a constant that depends on both the value of k and the value of y.

I believe the solution involves computing some sort of "distance across y" between k % y and k % (y + 1).

Hoping this is easy for someone who studied mathematics, rather than comp sci, as I'm out of my league here. Thanks!

$\endgroup$
0
$\begingroup$

You have $k=my+r$ for some $m,r$ and $k\%y=r=k-my$. Now if you want $k'\%(y+1)=r$, you need $k'=m'(y+1)+r$. One way to assure this is to have $m'=m, k'=k+m$. Unfortunately, just having $k\%y$ you don't know $m$. Another way to assure this is to let $k=r$ but it seems you want $k'$ to depend upon $k$ somehow. Yet a third way is to set $k'=k(y+1)+r$ Do any of these meet your needs?

$\endgroup$
1
  • $\begingroup$ Ross, this is perfect and exactly what I was looking for. You saved me days. Thank you!! $\endgroup$ – MikeBRM Jun 28 '12 at 16:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.