I'm trying to find the fundamental solution for the $n = 61$ case of Pell's equation $x^2 - ny^2 = 1$ through continued fractions. I know the lowest solution is $x = 1766319049$, $y = 226153980$, but the continued fraction expansion for $\sqrt{61}$ appears to miss the case where this pair of values for the nominator and denominator occurs. This upsets me because the Wikipedia page for Pell's equation explains that calculating the continued fraction for $\sqrt{n}$ should solve the problem. What am I doing wrong?
This is the code I'm using:
double r = sqrt(61);
unsigned long long h1 = 0;
unsigned long long h2 = 1;
unsigned long long k1 = 1;
unsigned long long k2 = 0;
for(int i=0;i<100;i++) {
unsigned long long b = r;
unsigned long long temp = b * h2 + h1;
h1 = h2;
h2 = temp;
temp = b * k2 + k1;
k1 = k2;
k2 = temp;
r = (double) 1 / (double) (r - b);
}
To answer your question (and to echo @LordSharktheUnknown's comment), what you're doing wrong is right here:
That number, $r$, that you're computing, is not $\sqrt{61}$. It's an approximation to it using double-precision arithmetic. Playing around with a different language, perhaps using floats instead of doubles, I find that $61 - r^2$, which should be $0$, is about $7 \times 10^{-15}$, which is definitely not zero. So you're finding (sort of) the continued fraction for a number that is not $\sqrt{61}$; you should not be surprised that the results you get are of little use in saying anything about $\sqrt{61}$.