I’m guessing there was some mathmematical trick here that I was missing. I wasn’t sure how to find out how many values of n to test for each value of a. I first tried 1000 and that wasn’t the right answer. I noticed that 500 gave me a smaller value. I tried 2000 and got the right answer, so I guess what was good enough!
count = 0
for a in range(3, 1001):
Rmax = 0
print a
for n in range(2000):
r = ((a-1)**n + (a+1)**n) % a**2
if r > Rmax:
Rmax = r
count += Rmax
print count