py求助,超时比较严重,有人能提供一下优化方法吗

P1217 [USACO1.5] 回文质数 Prime Palindromes

F_Suzichen @ 2022-12-23 15:42:08

import math

a,b=input().split()
a=int(a)
b=int(b)
c=[]
d=[]
def spi(h):
    for i in range(2,int(math.sqrt(h)+1)):
        if h%i==0:
            return 0
    else:
        return 1
for i in range(a,b+1):
    if spi(i):
        j=str(i)
        c.append(j)

for i in c:
    t=i[::-1]
    if t in i:
        d.append(i)

for i in d:
    print(i)

by 心灵震荡 @ 2022-12-23 15:50:43

@F_Suzichen 先制造符合要求的回文数,再一一查看是否在给定区间内


by OldDriverTree @ 2022-12-23 16:18:22

@F_Suzichen 打表他不香吗?


by Lucas2024 @ 2022-12-25 17:02:25

制造回文数然后判断,注意回文数一点要在a和b之间


by _8008008 @ 2022-12-29 10:07:43

复制输出弄成列表


|