python 44 tle了,求大佬帮忙

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

Winds_Land @ 2024-01-27 12:12:27

a,b = map(int,input().split())
# 判断是否为素数
def is_prime(num):
    for i in range(2,int(num**1/2)):
        if num % i == 0:
            return 0
    return 1
# 判断是否为回文数
def is_palindrome(num):
    s = str(num)
    if s == s[::-1]:
        return 1
    return 0

for i in range(a,b+1):
    if is_palindrome(i) and is_prime(i):
        print(i)

by Winds_Land @ 2024-01-27 12:42:39

a,b = map(int,input().split())
# 判断是否为素数
def is_prime(num):
    if num%2==0:
        return 0
    for i in range(3,int(num**1/2)+1,2):
        if num % i == 0:
            return 0
    return 1
# 判断是否为回文数
def is_palindrome(num):
    s = str(num)
    if s == s[::-1]:
        return 1
    return 0

for i in range(a,b+1):
    if is_palindrome(i) and is_prime(i):
        print(i)

改了下质数的判断,现在55了,还有改进空间


by Winds_Land @ 2024-01-27 19:13:03

用了埃式筛,结果4个TLE还有最后一个MLE了

a,b = map(int,input().split())
# 埃式筛
# 核心思想:每找到一个质数,将其倍数全部删除
def get_prime(n):
  # vis 表示是否删除
    vis = [0] * (n + 1)
    vis[0]=vis[1]=0
    # 质数列表
    prime = []
    # 从小到大,找到第一个未被标记的数,就是质数
    for i in range(2,n+1):
        if vis[i]==0:
            prime.append(i)
            # 找到质数后删除其倍数
            for j in range(i+i,n+1,i):
                vis[j]=1
    return prime
# 判断是否为回文数
def is_palindrome(num):
    s = str(num)
    if s == s[::-1]:
        return 1
    return 0
prime = get_prime(b)
for i in prime:
    if i>=a and is_palindrome(i):
        print(i)

|