def issq(x): sqr = int(x ** 0.5) if sqr ** 2 == x: return True return False def con_frac(num): a, b = 0, 1 para = [] while b and (a, b) not in para: d = int((num ** 0.5 + a) / b) yield d para.append((a, b)) a = b * d - a b = (num - a ** 2) // b def con2frac(con_list): a, b = 1, 0 for r in reversed(con_list): a, b = b + a * r, a return a, b def solve(d): x, y = con2frac(list(con_frac(d))[:-1]) if x ** 2 - d * y ** 2 == 1: return (x, y) else: return (2 * x * y, x ** 2 + d * y ** 2) def search(limit): for num in range(2, limit + 1): yield solve(num)[1], num print(max(search(1000))[1])