(Python)
import math
def is_square(n: int) -> bool:
if n < 0: return False
r = math.isqrt(n)
return r * r == n
def a(n: int) -> int: # by solving a Pell equation
if is_square(n): return 0
x = 3
while True:
if is_square(n * x * x + (1 - n)):
d, m = divmod(x * x - 1, 8)
if m == 0: return d
x += 2
(Python)
from sympy.ntheory.primetest import is_square
from sympy.solvers.diophantine.diophantine import diop_DN
if is_square(n): return 0
c, a, b = None, diop_DN(n, 1-n), diop_DN(n, 1)
while c is None:
a2 = []
for r, s in a:
if (sa:=abs(s))>1 and sa&1:
c = min(c, sa) if c is not None else sa
for t, u in b:
w, d = r*u+s*t, r*t+s*u*n
if (wa:=abs(w))>1 and wa&1:
c = min(c, wa) if c is not None else wa
a2.extend([(d, w), (d, -w), (-d, w), (-d, -w)])
a.extend(a2)