So problem #120 says:
Let r be the remainder when (a−1)^n + (a+1)^n is divided by a^2.
For example, if a = 7 and n = 3, then r = 42: 6^3 + 8^3 = 728 ≡ 42 mod 49. And as n varies, so too will r, but for a = 7 it turns out that rmax = 42.
For 3 ≤ a ≤ 1000, find ∑ rmax.
If we start putting various values into the equation for n and expanding the equation we notice a pattern emerging. If n is even the last term which is the only term not evenly divisible by a^2 is 2 which is a constant. However for odd values of n the last term ends up being 2*n*a. A little more tinkering on pencil and paper shows us that n = (a – 1)/2 so that means for any value a the rmax is equal to 2*a*((a-1)/2).
The solution below runs in about 3 hundredths of a second (according to linux’s time command). Provided in mono/c#.
using System;
using System.Diagnostics;
namespace Problem120
{
class MainClass
{
public static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
int sum = 0;
for (int a = 3; a <= 1000; a++)
{
sum += 2 * a * ((a - 1) / 2);
}
Console.WriteLine(sum);
sw.Stop();
Console.WriteLine(sw.Elapsed);
Console.ReadLine();
}
}
}