This algorithm due to Lagrange gives the expansion as a continued fraction of a quadratic number
(u+√D)/v, with u, v, D integers, D not a square.
The algorithm requires v dividing D-u².
If v doesn't divide D-u², we can replace u by u|v|, D by Dv² and v by v|v| then v|v| divides Dv²-u²v²,
although being the same quadratic number.
|Let U0=u, V0=v, a=E[√D],
With E[x]=integer part of x (ceil function).
And added variables X, Y, P X-1=-u, X0=v
then repeat for i≥0:
until sequence Vn becomes periodic.
The ai are the terms of the continued fraction,
Pi/Yi are the convergents