TITLE: Function which creates the sequence 1, 2, 3, 1, 2, 3, ...
QUESTION [41 upvotes]: I was wondering how to map the set $\mathbb{Z}^+$ to the sequence $1, 2, 3, 1, 2, 3, \ldots$. I thought it would be easy, but I was only able to obtain an answer through trial and error.
For a function $f \colon \mathbb{Z}^+ \rightarrow \mathbb{Z}$, we have that
$f(x) = x \bmod 3$ gives the numbers $1, 2, 0, 1, 2, 0, \ldots$
$f(x) = (x \bmod 3) + 1$ gives the numbers $2, 3, 1, 2, 3, 1, \ldots$
After a bit of experimenting, I finally found that
$f(x) = ((x + 2) \bmod 3) + 1$ gives the numbers $1, 2, 3, 1, 2, 3, \ldots$
More generally, if I want to map the set $\mathbb{Z}^+$ to the sequence $\{1, 2, \ldots, n, 1, 2, \ldots, n, \ldots\}$, I need to use the function
$$f(x) = ((x + n - 1) \bmod n) + 1$$
I was only able to come to this result by trial and error. I was not able to find a solution to this relatively simple question online (although perhaps my search terms were off).
How would one come to this result in a more systematic way?

REPLY [2 votes]: Your only problem is that you're counting up from one.  If you started counting from zero, then $$f(x) = x \bmod 3$$ would do the job, generating the output sequence $0,1,2,0,1,2,0,1,2,\dots$ when applied to the input sequence $0,1,2,3,4,5,6,7,8,\dots$.
But if you insist on one-based counting, then you simply need to shift the input down by one, and the output correspondingly up by one, as in $$f(x) = ((x-1) \bmod 3) + 1.$$  This will generate the output sequence $1,2,3,1,2,3,1,2,3,\dots$ when applied to the input sequence $1,2,3,4,5,6,7,8,9,\dots$.