Remainder is Primitive Recursive

Theorem
Let $m, n \in \N$ be natural numbers.

Let us define the function $\operatorname{rem}: \N^2 \to \N$:


 * $\operatorname{rem} \left({n, m}\right) = \begin{cases}

\text{the remainder when } n \text{ is divided by } m & : m \ne 0 \\ 0 & : m = 0 \end{cases}$

where the $\text{remainder}$ is as defined in the Division Theorem:
 * If $n = m q + r$, where $0 \le r < m$, then $r$ is the remainder.

Then $\operatorname{rem}$ is primitive recursive.

Proof
Let $\operatorname{rem} \left({n, m}\right) = r$.

We see that as $n$ increases by $1$, then so does $r$, except when $n = m-1$ in which case increasing $n$ by $1$ makes $r$ go to $0$.

We also take into account the case where $m = 0$:

So we can define $\operatorname{rem}$ by cases:
 * $\operatorname{rem} \left({n, m}\right) = \begin{cases}

0 & : \operatorname{rem} \left({n-1, m}\right) = m - 1 \text { or } m = 0 \text { or } n = 0\\ \operatorname{rem} \left({n-1, m}\right) + 1 & : \text {otherwise} \\ \end{cases}$

We remind ourselves of the following primitive recursive functions:


 * Signum function $\operatorname{sgn}$;
 * Characteristic function of equality relation $\chi_{\operatorname{eq}} \left({n, m}\right)$;
 * Cut-off subtraction $m \, \dot - \, n$.

We have:
 * $\operatorname{sgn} \left({m}\right) = 1 \iff m \ne 0$;
 * $\overline {\operatorname{sgn}} \left({\chi_{\operatorname{eq}} \left({\operatorname{rem} \left({n, m}\right), m \, \dot - \, 1}\right)}\right) = 1 \iff \operatorname{rem} \left({n, m}\right) \ne m \, \dot - \, 1$.

So:
 * $\operatorname{sgn} \left({m}\right) \overline {\operatorname{sgn}} \left({\chi_{\operatorname{eq}} \left({\operatorname{rem} \left({n, m}\right), m \, \dot - \, 1}\right)}\right) = 1 \iff m > 0 \land \operatorname{rem} \left({n, m}\right) \ne m \, \dot - \, 1$.

So we see that:
 * $\operatorname{rem} \left({n + 1, m}\right) = \left({\operatorname{rem} \left({n, m}\right) + 1}\right) \operatorname{sgn} \left({m}\right) \overline {\operatorname{sgn}} \left({\chi_{\operatorname{eq}} \left({\operatorname{rem} \left({n, m}\right), m \, \dot - \, 1}\right)}\right)$

So $\operatorname{rem}$ is obtained by primitive recursion (over the first variable, which is allowed by Permutation of Variables of Primitive Recursive Function) from the primitive recursive functions:
 * Signum function $\operatorname{sgn}$
 * Characteristic function of equality relation $\chi_{\operatorname{eq}} \left({n, m}\right)$
 * Cut-off subtraction $m \, \dot - \, n$
 * Addition
 * Multiplication.

Thus we can use Definition by Cases is Primitive Recursive and it follows that $\operatorname{rem}$ is primitive recursive.