Lower-half quadratic-residue sum for primes congruent to seven modulo eight (source code)

= Lower-half quadratic-residue sum for primes congruent to seven modulo eight

For a <prime number> $p\equiv7\pmod8$, let $L$ be the sum of the least positive <quadratic residues> below $p/2$. Then
$$
L=\frac{p^2-1}{16}.
$$
For example, at $p=23$ the relevant <quadratic residues> are $1,2,3,4,6,8,9$, and their sum is $33=(23^2-1)/16$.

To prove the identity, put $m=(p-1)/2$, let $S$ be the sum of all least positive nonzero <quadratic residues>, and let $b$ count those above $p/2$. The <second supplementary law for quadratic reciprocity> gives $(2/p)=1$, so doubling permutes these <residue classes>. Reducing each doubled representative modulo $p$ subtracts $p$ exactly $b$ times. Hence $S=2S-pb$, or $S=pb$.

Since $p\equiv3\pmod4$, the <first supplementary law for quadratic reciprocity> says $-1$ is a <quadratic nonresidue>. Exactly one of $j,p-j$ is therefore a <quadratic residue> for each $1\le j\le m$. The lower-half choices sum to $L$; the upper-half choices sum to $pb-(1+\cdots+m-L)$. Consequently
$$
S=2L+pb-\frac{m(m+1)}2.
$$
Substituting $S=pb$ gives $L=m(m+1)/4=(p^2-1)/16$. Both congruence conditions have a role: one makes doubling a permutation, and the other makes each opposite pair contain exactly one <quadratic residue>.