The shortest path in number theory [closed]

Given non-negative integers $a$ and $b$ that are smaller than $1\,000\,000$, find the shortest path between them in the sense of $\text{mod}$. Let's measure the length of the path by how much steps it take. Starting from number $a$, in each step we can choose from $(1)$ to $(4)$:

$(1)$ add $1$,

$(2)$ add $-1$,

$(3)$ add $1000$,

$(4)$ add $-1000$.

And after that, $\text{mod}$ $1\,000\,000$. My question is, how to write a concise expression to calculate the length of the shortest path (i.e., the distance) between $a$ and $b$, by using some $\min\left\{\right\}$ and $\text{mod}$? I encountered this question when I am programming. It's kind of like measuring the distance between two points on a ball. But here we don't have the great circle. I can duplicate the "ball" and put them in a plane to illustrate them. Maybe it could help? the "ball"


A couple notes to simplify the computation:

  • the distance from $a$ to $b$ is the same as the distance from $b$ to $a$, so we may assume $a \leq b$.
  • the distance from $a$ to $b$ is the same as the distance from $0$ to $b-a$, so we may assume $a=0$.
  • The distance from $0$ to $b$ is the same as the distance from $0$ to $1000000-b$, so we may assume $b \leq 500000$.
  • By the division algorithm, $b = 1000m + n$ where $m,n \geq 0$ and $n < 1000$.

Under these simplifications, the distance you want is $$m + \min\Big(n, 1001-n\Big)$$


By unraveling the above steps,

x = min(|b-a|, 1000000-|b-a|)
m = x // 1000         (// is integer division)
n = x % 1000          (% is the modulo operator)
answer = m + min(n, 1001-n)

If you wish, you can put this all on one line, but I see no reason to do so.