Project Euler 808

Project Euler 808

题目

Reversible prime squares

Both $169$ and $961$ are the square of a prime. $169$ is the reverse of $961$.

We call a number a reversible prime square if:

  1. It is not a palindrome, and
  2. It is the square of a prime, and
  3. Its reverse is also the square of a prime.

$169$ and $961$ are not palindromes, so both are reversible prime squares.

Find the sum of the first $50$ reversible prime squares.

解决方案

直接使用sympy库中的nextprime暴力枚举质数进行判断,需要注意不要漏掉第一个条件。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from tools import is_prime, is_square, int_sqrt
from sympy import nextprime

N = 50


def ok(n):
s = str(n)
t = s[::-1]
if s == t:
return False
m = int(t)
return is_prime(int_sqrt(m)) if is_square(m) else False


p = 1
ans = 0
while True:
p = nextprime(p)
if ok(p * p):
ans += p * p
N -= 1
if N == 0:
break
print(ans)

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
Ujimatsu Chiya 微信 微信
Ujimatsu Chiya 支付宝 支付宝