TITLE: First coefficient of totally positive fundamental unit modulo 3
QUESTION [19 upvotes]: Suppose $p$ is a prime number such that $p\equiv 7 \pmod{12}$.
Since $p \not \equiv 1 \mod{4}$, the ring of integers of $\mathbb{Q}(\sqrt{p})$ is $\mathbb{Z}\oplus\mathbb{Z}(\sqrt{p})$ with fundamental unit of the form $a+b\sqrt{p}$, where $a, b > 0$
It is of the norm $+1$, because $a^2 - pb^2 \equiv -1 \pmod{4}$ doesn't have solutions when $p\equiv -1 \pmod{4}$.
It is easy to see that $a\equiv \pm 1 \pmod{3}$, since if $3|a$, then $a^2 - pb^2 \equiv - b^2 \not\equiv 1 \pmod{3}$

A computer-checked observation.  For all said $p$ such that $p<20000$ the following holds: $a\equiv -1 \pmod{3}$

That, I think, is rather surprising. I tried proving that $a\equiv -1$ for the case when the period of continued fraction for $\sqrt{p}$ is of length $4$, but got nowhere.
The claim is false when $p$ is not prime, for example $\mathbb{Q}(115)$ has the fundamental unit $1126+105\sqrt{115}$. It is also false when we drop modulo conditions, say, in $\mathbb{Q}(\sqrt{11})$ the fundamental unit is $10+3\sqrt{11}$
What is known about coefficients of the continued fraction for $\sqrt{p}$ ? I only know that it is of the form $[a_o; \overline{a_1, a_2, ..., a_2, a_1, 2a_0}]$ and that when the class number of the field is 1, the sum $a_1 - a_2 + a_3 - ... \pm 2a_0$ is divisible by 3 (the latter is a corollary from a theorem by Don Zagier).
All that cannot even preclude the case when all coefficients of the continued fraction are divisible by 3.
Any hints are welcome.

REPLY [14 votes]: By Theorem 1.1 of Zhang-Yue: Fundamental units of real quadratic fields of odd class number, J. Number Theory 137 (2014), 122-129, we have that $a\equiv 0\pmod{2}$. From here it is a simple matter to prove that $a\equiv 2\pmod{3}$, hence in fact $a\equiv 2\pmod{6}$. To see this, let us write
the unit equation as
$$(a-1)(a+1)=pb^2.$$
The left hand side is divisible by $3$, hence so is $b$. The factors on the left hand side are odd and coprime, so they are of the form $pb_1^2$ and $b_2^2$ in some order, where $b=b_1b_2$. Note that exactly one of the $b_i$'s is divisible by $3$. Therefore, adding the factors of the left hand side, we get modulo $3$ that
$$2a=pb_1^2+b_2^2\equiv b_1^2+b_2^2\equiv 1\pmod{3}.$$
Hence $a\equiv 2\pmod{3}$ as claimed.