k = 2 + 5 ** 0.5 out = [] maxx = 12 m = 4 n = 1 def test(x, y): b2 = 4 * x * y h = x ** 2 - y ** 2 if abs(h - b2) == 1: #print b2, h, x, y out.append(x ** 2 + y ** 2) return True return False while len(out) < maxx: m = int(k * n) - 1 for i in [0,1,2]: if test(m + i, n): #print out[-1] n = m n += 1 print sum(out)