Example 3 Find all positive integers $n$ such that $n^{2} \mid\left(2^{n}+1\right)$.
(31st IMO)
First, we prove a lemma using mathematical induction.
Lemma If $3 \|(a+1)$, then for any $k \in \mathbf{N}$, $3^{k+1} \|\left(a^{3^{k}}+1\right)$.
Proof: When $k=0$, according to the condition, the conclusion is obviously true.
Assume that when $k=t$, $3^{t+1} \|\left(a^{3^{k}}+1\right)$.
Then when $k=t+1$,
$$
a^{3^{t+1}}+1=\left(a^{3^{t}}+1\right)^{3}-3 a^{3^{t}}\left(a^{3^{t}}+1\right) \text {. }
$$

According to the induction hypothesis,
$$
3^{3(t+1)} \mid\left(a^{3^{t}}+1\right)^{3}, 3^{t+2} \| 3 a^{3^{t}}\left(a^{3^{t}}+1\right) \text {. }
$$

Therefore, $3^{t+2} \|\left(a^{3^{t+1}}+1\right)$.
Back to the original problem.
When $n=1$, it obviously satisfies the condition.
Assume $n>1$.
Since $2^{n}+1$ is an odd number, and $n^{2} \mid\left(2^{n}+1\right)$, thus, $n$ is an odd number.
Therefore, $(2, n)=1$.
Let the smallest prime factor of $n$ be $p$. Then
$$
p \mid\left(2^{n}+1\right) \Rightarrow 2^{n} \equiv-1(\bmod p) \text {. }
$$

Let the semi-order of 2 modulo $p$ be $\tau$. Then $\tau \mid n$.
Also, according to Fermat's Little Theorem,
$$
\begin{array}{l}
2^{p-1} \equiv 1(\bmod p) \\
\Rightarrow 2 \tau \mid (p-1) \Rightarrow \tau \mid (p-1, n) .
\end{array}
$$

Noting that $p$ is the smallest prime factor of $n$.
Thus, $(p-1, n)=1 \Rightarrow \tau=1$
$\Rightarrow 2 \equiv-1(\bmod p) \Rightarrow p=3$.
Let $n=3^{\alpha} m\left(\alpha \in \mathbf{Z}_{+}, m \in \mathbf{Z}_{+},(m, 6)=1\right)$.
Since $n^{2} \mid\left(2^{n}+1\right)$, thus,
$$
3^{2 \alpha} \mid\left(2^{3^{\alpha} m}+1\right) \Rightarrow 3^{2 \alpha} \mid\left[\left(2^{m}\right)^{3^{\alpha}}+1\right] \text {. }
$$

On the other hand, since the semi-order of 2 modulo 3 is 1, and modulo 9 is 3, and $(m, 6)=1$, thus,
$3 \|\left(2^{m}+1\right)$.
By the lemma, $3^{\alpha+1} \|\left(2^{3^{\alpha} m}+1\right)$.
Combining both aspects, we have
$$
2 \alpha \leqslant \alpha+1 \Rightarrow \alpha=1
$$
$\Rightarrow n=3 m$, where $m \in \mathbf{Z}_{+},(m, 6)=1$.
If $m=1$, then $n=3$, which satisfies the condition.
If $m>1$, let the smallest prime factor of $m$ be $q$, then $q \geqslant 5$.
Thus, $q^{2} \mid\left(2^{3 m}+1\right) \Rightarrow 8^{m} \equiv-1(\bmod q)$.
Let the semi-order of 8 modulo $q$ be $\tau_{1}$. Then $\tau_{1} \mid m$.
Also, according to Fermat's Little Theorem,
$$
8^{q-1}=1(\bmod q) \text {. }
$$

Therefore, $2 \tau_{1} \mid (q-1) \Rightarrow \tau_{1} \mid (m, q-1)$.
Noting that $q$ is the smallest prime factor of $m$.
Thus, $(m, q-1)=1$.
Hence, $\tau_{1}=1$.
Therefore, $8 \equiv-1(\bmod q) \Rightarrow q=3$.
This contradicts $q \geqslant 5$.
In summary, the solutions that satisfy the condition are only $n=1,3$.