Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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!

share|cite|improve this question
up vote 0 down vote accepted

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?

share|cite|improve this answer
Ross, this is perfect and exactly what I was looking for. You saved me days. Thank you!! – MikeBRM Jun 28 '12 at 16:35

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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