Skip to content

Commit db0746b

Browse files
author
Ravi Kandasamy Sundaram
committed
problem_123: project euler solution 120
Name: Prime square remainders Let pn be the nth prime: 2, 3, 5, 7, 11, ..., and let r be the remainder when (pn−1)^n + (pn+1)^n is divided by pn^2. For example, when n = 3, p3 = 5, and 43 + 63 = 280 ≡ 5 mod 25. The least value of n for which the remainder first exceeds 10^9 is 7037. Find the least value of n for which the remainder first exceeds 10^10. Reference: https://projecteuler.net/problem=123 Fixes: #2695
1 parent c9500dc commit db0746b

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

Diff for: project_euler/problem_123/__init__.py

Whitespace-only changes.

Diff for: project_euler/problem_123/sol1.py

+85
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
"""
2+
"https://projecteuler.net/problem=123"
3+
4+
Name: Prime square remainders
5+
6+
Let pn be the nth prime: 2, 3, 5, 7, 11, ..., and
7+
let r be the remainder when (pn−1)^n + (pn+1)^n is divided by pn^2.
8+
9+
For example, when n = 3, p3 = 5, and 43 + 63 = 280 ≡ 5 mod 25.
10+
The least value of n for which the remainder first exceeds 10^9 is 7037.
11+
12+
Find the least value of n for which the remainder first exceeds 10^10.
13+
14+
15+
Solution:
16+
17+
n=1: (p-1) + (p+1) = 2p
18+
n=2: (p-1)^2 + (p+1)^2
19+
= p^2 + 1 - 2p + p^2 + 1 + 2p (Using (p+b)^2 = (p^2 + b^2 + 2pb),
20+
(p-b)^2 = (p^2 + b^2 - 2pb) and b = 1)
21+
= 2p^2 + 2
22+
n=3: (p-1)^3 + (p+1)^3 (Similarly using (p+b)^3 & (p-b)^3 formula and so on)
23+
= 2p^3 + 6p
24+
n=4: 2p^4 + 12p^2 + 2
25+
n=5: 2p^5 + 20p^3 + 10p
26+
27+
As you could see, when the expression is divided by p^2.
28+
Except for the last term, the rest will result in the remainder 0.
29+
30+
n=1: 2p
31+
n=2: 2
32+
n=3: 6p
33+
n=4: 2
34+
n=5: 10p
35+
36+
So it could be simplified as,
37+
r = 2pn when n is odd
38+
r = 2 when n is even.
39+
"""
40+
41+
42+
def sieve() -> int:
43+
"""
44+
Returns a prime number generator using sieve method.
45+
"""
46+
D = {}
47+
q = 2
48+
while True:
49+
p = D.pop(q, None)
50+
if p:
51+
x = p + q
52+
while x in D:
53+
x += p
54+
D[x] = p
55+
else:
56+
D[q * q] = q
57+
yield q
58+
q += 1
59+
60+
61+
def square_remainder(p, n) -> int:
62+
"""
63+
Returns the square remainder with a simplified expression.
64+
"""
65+
return 2 * p * n
66+
67+
68+
def solution(limit: int = 1e10) -> int:
69+
"""
70+
Returns the least value of n for which the remainder first exceeds 10^10.
71+
"""
72+
primes = sieve()
73+
74+
n = 1
75+
while True:
76+
p = next(primes)
77+
if square_remainder(p, n) > limit:
78+
return n
79+
# Ignore the next prime as the reminder will be 2.
80+
next(primes)
81+
n += 2
82+
83+
84+
if __name__ == "__main__":
85+
print(solution())

0 commit comments

Comments
 (0)