40. Find all positive integers $n$ and non-negative integers $x_{1}, x_{2}, \cdots, x_{n}$, such that $\sum_{i=1}^{n} x_{i}^{2}=1+\frac{4}{4 n+1}\left(\sum_{i=1}^{n} x_{i}\right)^{2}$.
(2002, Taiwan Mathematical Olympiad)
Let $X=x_{1}+x_{2}+\cdots+x_{n}$. If $x_{i} \leqslant 1, i=1,2,3, \cdots, n$, denote
$$
|I\{i \mid x_{i}=1\}|=a,|\{i \mid x_{1}=0\}|=n-a .
$$

Then the equation can be rewritten as
$$
a=1+\frac{4 a^{2}}{4 n+1} .
$$

It is easy to see that $a \neq 1$, so
$4 n+1=4(a+1)+\frac{4}{a-1}$.
Solving this, we get $a=5, n=6$.
Assume there exists some $i$ such that $x_{1} \geqslant 2$. Then,
$$
X+1 \leqslant \sum_{i=1}^{n} x_{i}^{2}=1+\frac{4}{4 n+1} \cdot X^{2} .
$$

Thus, $1 \leqslant \frac{4}{4 n+1} \cdot X$, which implies $X \geqslant \frac{4 n+1}{4}=n+\frac{1}{4}$.
Since $X$ is an integer, we have $X \geqslant n+1$.
On the other hand, from $\frac{X^{2}}{n} \leqslant \sum_{i=1}^{n} x_{i}^{2}=1+\frac{4}{4 n+1} \cdot X^{2}$, we get $X^{2} \leqslant 4 n^{2}+n \Rightarrow X \leqslant 2 n$.
Therefore, $n+1 \leqslant X \leqslant 2 n$, so
$1<1+\frac{1}{n} \leqslant \frac{X}{n} \leqslant 2$.
Since $\sum_{i=1}^{n}\left(x_{i}-\frac{X}{n}\right)^{2}=\sum_{i=1}^{n} x_{i}^{2}-\frac{X^{2}}{n}=1-\frac{X^{2}}{n(4 n+1)} < 1$, we have
$$
-1<x_{i}-\frac{X}{n}<1, \forall i=1,2, \cdots, n .
$$

Thus, $0<-1+\frac{X}{n}<x_{i}<1+\frac{X}{n} \leqslant 3$.
Hence, $x_{i} \in\{1,2\}, \forall i=1,2, \cdots, n$.
Let $|\{i \mid x_{i}=2\}|=b, |\{i \mid x_{i}=1\}|=n-b$. Then the given equation becomes
$$
3 b+n=1+\frac{4}{4 n+1}(b+n)^{2} .
$$

So, $n=\frac{1}{4 b-3}+b$.
Thus, $b=1, n=2$.
In summary, the solutions to the equation are:
(1) When $n=6$, $\left(x_{1}, x_{2}, x_{3}, x_{4}, x_{5}, x_{6}\right)=(0,1,1,1,1,1)$, $(1,0,1,1,1,1)$, $(1,1,0,1,1,1)$, $(1,1,1,0,1,1)$, $(1,1,1,1,0,1)$, or $(1,1,1,1,1,0)$;
(2) When $n=2$, $\left(x_{1}, x_{2}\right)=(1,2)$ or $(2,1)$.