I am facing a problem in modular arithmetic.
Simplified problem statement:
n: an integer, the number of prisoners
m: an integer, the number of sweets
s: an integer, the chair number to begin passing out sweets fromThe prisoners are seated around a circular table in sequentially numbered chairs (numbering starts from 1).
Find the prisoner who receives the last sweet.
I can think of many possible solutions but decided to try a one liner:
m % n + s - 1
My reasoning:
Distribute
msweets tonprisoners evenly. The remainder will be part of the last round of distribution.Add the initial offset
sto reach the last seat.I had to subtract 1 from the result to pass some test cases (I don't know the reason).
However, the formula fails for other test cases.
What is going wrong in the logic? How should I correct the formula?
The reason you have to subtract $1$ is to avoid what is known as a fencepost error or "off-by-one" error. Suppose there is only $1$ sweet. Then starting at seat $s$ you know the last (and only) sweet will go to the pirsoner at seat $s$. But $m\%n+s$ gives the result $s+1$. You need the $-1$ adjustment in $m\%n+s-1$ to account for the fact that sweet $1$ is given to the prisoner at setat $s$, not at seat $s+1$.
The other thing you have to remember is that $m\%n$ gives a result between $0$ and $n-1$, so $m\%n+s-1$ will be between $s-1$ and $n+s-2$. But the seat numbers go from $1$ to $n$. You could adjust your formula to $(m+s-1)\%n$, which is correct most of the time, but gives the incorrect answer $0$ when $m+s-1$ is a multiple of $n$. I'll leave you to think about how to make another adjustment to this expression to get an answer that is correct in all cases.