Continuous and discontinuous function problem

Here is one that works for $n=2$:

Let $f(x) = 0$ if $x$ is rational and $1$ if $x$ is irrational.

Then $f(x)$ is discontinuous for all $x$ but $f(f(x))=0$ for all $x$ and is continuous.

At the moment, I don't see how to delay the result of $n-1$ iterations of $f$ to only rational values while the previous iterations can be anywhere.


Fix $x_1,x_2,\ldots,x_n\in\mathbb R$ which are linearly independent over $\mathbb Q$. For each $\alpha\in\mathbb Q$, let $f(\alpha x_1)=0$ and $f(\alpha x_i)=x_{i-1}$ for $i=2,\ldots,n$; let $f(x)=0$ for all other $x\in\mathbb R$. Clearly $f$ composed with itself $n$ times is the zero function which is continuous. For $k<n$, $f$ composed with itself $k$ times sends the dense subset $\{\alpha x_{k+1}\,:\,\alpha\in\mathbb Q\}$ to $x_1\neq0$ and the dense subset $\{\alpha x_{k}\,:\,\alpha\in\mathbb Q\}$ to $0$. Hence this function is nowhere continuous.


Let $A_{n}$ denote the set of real numbers which solve an integer polynomial of degree $n$, but are not roots of any polynomial of degree $< n$. Then $A_{1} = \mathbb{Q}$, and $A_{2}$ is the set of all irrational (real) solutions to quadratic polynomials, etc. Let \begin{align*} f(x) & = \begin{cases} 0 & \textrm{if } x \not \in A_{1}, \ldots, A_{n}, \\ 2 & \textrm{if } x \in A_{1} , A_{2} , \\ \sqrt{2} & \textrm{if } x \in A_{3} , \\ 2^{1 / 3} & \textrm{if } x \in A_{4} , \\ \vdots & \vdots \\ 2^{1 / (n - 1)} & \textrm{if } x \in A_{n} . \end{cases} \end{align*} That should do it, I'm pretty sure.