|
| 1 | +""" |
| 2 | +Problem 123: 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 | + >>> square_remainder(7, 5) |
| 65 | + 70 |
| 66 | + >>> square_remainder(11, 10) |
| 67 | + 220 |
| 68 | + >>> square_remainder(13, 5) |
| 69 | + 130 |
| 70 | + """ |
| 71 | + return 2 * p * n |
| 72 | + |
| 73 | + |
| 74 | +def solution(limit: int = 1e10) -> int: |
| 75 | + """ |
| 76 | + Returns the least value of n for which the remainder first exceeds 10^10. |
| 77 | + >>> solution(1e8) |
| 78 | + 2371 |
| 79 | + >>> solution(1e9) |
| 80 | + 7037 |
| 81 | + """ |
| 82 | + primes = sieve() |
| 83 | + |
| 84 | + n = 1 |
| 85 | + while True: |
| 86 | + p = next(primes) |
| 87 | + if square_remainder(p, n) > limit: |
| 88 | + return n |
| 89 | + # Ignore the next prime as the reminder will be 2. |
| 90 | + next(primes) |
| 91 | + n += 2 |
| 92 | + |
| 93 | + |
| 94 | +if __name__ == "__main__": |
| 95 | + print(solution()) |
0 commit comments