def gen_tri(limit): tale = 1 base = 1 while tale < limit: yield (base, tale) base += 1 tale += base def tri_pair(num): seq = int(((8 * num - 1) ** 0.5 - 1) / 2) return ((seq , (seq + 1) * seq // 2), (seq + 1, (seq + 1) * (seq + 2) // 2)) def renew(result, limit, t_n, t_o): cmpr = t_n[1] * t_o[1] new_result = [max(limit, cmpr) - min(limit, cmpr), t_n[0] * t_o[0]] if new_result[0] < result[0]: return new_result else: return result def search(limit): result = [limit, 0] for t_n in gen_tri(int(limit ** 0.5) + 1): t_l, t_r = tri_pair(limit // t_n[1]) result = renew(result, limit, t_n, t_l) result = renew(result, limit, t_n, t_r) return result[1] print(search(2000000))