用python超时怎么办

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

sscyy @ 2024-03-18 20:30:55

a,b=map(int,input().split())

def is_prime(num):

    if num<2:
       return False
    for i in range(2,int(num**0.5)+1):
       if num%i==0:
           return False
    return True

def huiwen(num):

      return str(num)==str(num)[::-1]

for i in range(a,b+1):

     if is_prime(i) and huiwen(i):
         print(i)

by NC20061226 @ 2024-03-18 20:34:26

嗯,这题应该不能用 Python 吧?(C艹都有可能超时。


by yanghb666 @ 2024-03-23 15:56:58

看看AC代码:

from math import *
z=[5,7,11]
x=[int(i) for i in input().split()]
for i in range(1,10,2):
    for j in range(0,10):
        for k in range(0,10):
            a=i*10000+j*1000+k*100+j*10+i
            for m in range(3,round(sqrt(a) + 1)):
                if a % m==0:
                    break
            else:
                z.append(a)
for i in range(1,10,2):
    for j in range(0,10):
        a=i*100+j*10+i
        for k in range(3,round(sqrt(a) + 1)):
            if a%k==0:
                break
        else:
            z.append(a)
for i in range(1,10,2):
    for j in range(0,10):
        for k in range(0,10):
            for l in range(0,10):
                a=1000000*i+j*100000+k*10000+l*1000+k*100+j*10+i
                for m in range(3,round(sqrt(a) + 1)):
                    if a % m == 0:
                        break
                else:
                    z.append(a)
z.sort()
for i in z:
    if x[0]<=i<=x[1]:
        print(i)

|