// you’re reading...
1 Star2 Stars3 Stars4 Stars5 Stars (9 votes, average: 5.00 out of 5)
Loading...

Solutions 101 - 150

Project Euler 120 Solution

Project Euler 120 Solution

Project Euler 120: Find the max remainder when (a − 1)n + (a + 1)n is divided by a2


Project Euler 120 Problem Description

Let r be the remainder when (a−1)n + (a+1)n is divided by a2.

For example, if a = 7 and n = 3, then r = 42: 63 + 83 = 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.

Analysis

A little investigation proves that for any value of a and any even value of n the remainder will always be 2. For odd values of n the remainder will be 2an. This remove’s any requirement to consider even n for a maximum remainder.

You can expand the polynomial for the first 8 values of n to get an idea of how this works:

Odd n: 1, 3, 5, 7 Even n: 2, 4, 6, 8
2a 2a2 + 2
2a3 + 6a 2a4 + 12a2 + 2
2a5 + 20a3 + 10a 2a6 + 30a4 + 30a2 + 2
2a7 + 42a5 + 70a3 + 14a 2a8 + 56a6 + 14a4 + 56a2 + 2

The last term becomes the remainder since the other terms are divisible by a2. Now we need to calculate which odd values of n will yield the largest remainder. This will save having to iterate different values of n.

We want to make 2n as close to a as possible; note that for even a the max remainder would be (a-2)*a and for odd a would be (a-1)*a. This is the same as rmax = (a−1) // 2 * 2 * a. So iterating through the range of a values we can accumulate the sum easily.

print sum((a-1)//2 * 2 * a for a in range(3, 1001))

An even easier way would be to use the formula that calculates the sum (source: Project Euler 120, Ben “beignet” Yey):

 \sum_{a=4, a\hspace{1mm}\mathrm{ even}}^{1000}(a^{2}-2a) \hspace{1mm} + \sum_{a=3,a\hspace{1mm}\mathrm{odd}}^{999}(a^{2}-a)

 \sum_{a=3}^{1000}a^{2}\hspace{1mm}- \sum_{a=3}^{1000}a\hspace{1mm}-\sum_{a=4, a\hspace{1mm}\mathrm{even}}^{1000}a
 \left[\sum_{i=1}^{1000}a^{2}\hspace{1mm}-(1+4)\right]- \sum_{i=3}^{1000}a\hspace{1mm}-2\sum_{i=2}^{500}a
 \left[\frac{1000(1001)(2001)}{6}-5\right]-\frac{998(1003)}{2}-2\frac{499(502)}{2}

Project Euler 120 Solution

Runs < 0.001 seconds in Python 2.7.
download arrowUse this link to get the Project Euler 120 Solution Python 2.7 source.

Afterthoughts

  • See also, Project Euler 123 Solution:
  • To solve this problem we do not require to consider values of n.
  • But, if we ever need to find which value of n yeilds a maximum remainder, we could expand the following series:
    n3=1, n4=1, n5=7, n6=5, n7=n3+2, n8=n4+2, n9=n5+6, n10=n6+4, n11=n6+2, n12=n7+2, n13=n8+6, n14=n9+4, …
  • Gratuitous table of rmax note the odd rmax = a2−a, even rmax = a2−2a
a nmax rmax
3 1 6
4 1 8
5 7 20
6 5 24

11 5 110
12 5 120
13 19 156
14 13 168
a nmax rmax
7 3 42
8 3 48
9 13 72
10 9 80

15 7 210
16 7 224
17 25 272
18 17 288

Discussion

No comments yet.

Post a comment