def issq(x): sqr = int(x ** 0.5) if sqr ** 2 == x: return True return False def div(sq, sub, quo): return (sq ** 0.5 + sub) / quo def cor(x): a = 0 b = 1 v = 0 out = [] ab = [] while 1: v = int(div(x, a, b)) tmp = b * v - a b = (x - tmp ** 2) / b a = tmp ab.append((a,b)) out.append(v) num = ab.index((a,b)) + 1 if num != len(ab): return out def pair(lis): a = 1 b = lis[0] for i in lis[1:]: a, b = b, b * i + a return (a,b) def sol(x): if issq(x): return (0, 0) pp = pair(cor(x)[-2::-1]) a = pp[0] b = pp[1] if b ** 2 - x * a ** 2 == 1: return (a, b) else: return (2 * a * b, b ** 2 + x * a ** 2) maxx = [0, 0] for i in xrange(2,1001): tmp = sol(i)[1] if tmp > maxx[0]: maxx = [tmp, i] print maxx