#!/usr/bin/env python3 def pell3(): x, y = 2, 1 while True: yield x, y x, y = 2*x + 3*y, 2*y + x max_perimiter = 10**9 s = 0 for x, y in pell3(): p = 12*(2*y**2 + x*y) + 2 if p <= max_perimiter: s += p p = 6*(x**2 - y**2) - 2 if p > max_perimiter: break s += p print(s)