A better recurrence?
With a bit of algebra, we can explain the recurrence relation in a more elegant way:
xn=1+anbnxn+1=1+12+anbn
It should be clear than 2+anbn=1+xn, so we can rewrite the second equation as:
xn+1=1+11+xnxn+1=2+xn1+xn
We are not actually interested in xn, but in the numerator and denominator of xn, thus if we have xn=pnqn, we can rewrite the last equation as:
xn+1=pn+1qn+1=2+pnqn1+pnqn=2qn+pnqnqn+pnqn=2qn+pnqn+pn
This recurrence is better than the one used in the previous solution, because it explicitly gives the numerator and denominator of xn.
From solution2.py:
def square_root_convergents():
pn = 1
qn = 1
count = 0
for _ in range(1000):
pn, qn = 2 * qn + pn, qn + pn
if len(str(pn)) > len(str(qn)):
count += 1
return count