def remainder(a: int, n: int) -> int: d = a * a return (pow(a - 1, n, d) + pow(a + 1, n, d)) % d def max_remainder(a: int) -> int: n, r_max = 1, 2 while True: r = remainder(a, n) if r == r_max: break if r > r_max: r_max = r n += 1 assert(r_max > 2) return r_max def euler_120(): assert(remainder(7, 3) == 42) assert(max_remainder(7) == 42) return sum([max_remainder(n) for n in range(3, 1001)]) if __name__ == "__main__": solution = euler_120() print("e120.py: " + str(solution)) assert(solution == 333082500)