Skip to content

Commit a8ad2d1

Browse files
authoredOct 6, 2020
Add Project Euler 120 solution (TheAlgorithms#2887)
1 parent a56e548 commit a8ad2d1

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed
 

‎project_euler/problem_120/__init__.py

Whitespace-only changes.

‎project_euler/problem_120/sol1.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
"""
2+
Problem 120 Square remainders: https://projecteuler.net/problem=120
3+
4+
Description:
5+
6+
Let r be the remainder when (a−1)^n + (a+1)^n is divided by a^2.
7+
For example, if a = 7 and n = 3, then r = 42: 6^3 + 8^3 = 728 ≡ 42 mod 49.
8+
And as n varies, so too will r, but for a = 7 it turns out that r_max = 42.
9+
For 3 ≤ a ≤ 1000, find ∑ r_max.
10+
11+
Solution:
12+
13+
On expanding the terms, we get 2 if n is even and 2an if n is odd.
14+
For maximizing the value, 2an < a*a => n <= (a - 1)/2 (integer division)
15+
"""
16+
17+
18+
def solution(n: int = 1000) -> int:
19+
"""
20+
Returns ∑ r_max for 3 <= a <= n as explained above
21+
>>> solution(10)
22+
300
23+
>>> solution(100)
24+
330750
25+
>>> solution(1000)
26+
333082500
27+
"""
28+
return sum(2 * a * ((a - 1) // 2) for a in range(3, n + 1))
29+
30+
31+
if __name__ == "__main__":
32+
print(solution())

0 commit comments

Comments
 (0)
Please sign in to comment.