又双叒叕超时辽,枯了

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

JerryWayne7 @ 2023-02-08 16:47:40

真的枯了,自己运行一切OK,提交上去就只AC了3个,6个超时,下面是代码,还请大佬们指点

a, b = map(int, input().split(" "))
for i in range(a, b + 1):

    flag1 = 1
    for j in range(2, int(i**0.5)+1):
        if i % j == 0:
            flag1 = 0

    flag2 = 1
    if i>= 10 and i!=11:
        a = []
        b = []
        count = 0
        for k in str(i):
            a.append(k)
            count += 1
        for m in range(count):
            b.append(a[count - 1 - m])
        for t in range(count):
            if (a[t] != b[t]):
                flag2 = 0

    if flag1 == 1:
        if flag2 == 1:
           print(i)

by JasonTesla @ 2023-02-08 17:12:40

flag等于零之后break掉能省一点时间但是还是会超时但是就只有一个


by JasonTesla @ 2023-02-08 17:15:08

假如说用C++的话应该不会因为我的python break掉之后还是有一个tlec++更快一点


by JerryWayne7 @ 2023-02-08 20:27:35

@JasonTesla 谢谢啦!刚刚用c++写的只剩4个tle了


by JasonTesla @ 2023-02-08 21:00:25

给你个参考代码python的只有一个超时的点c++应该更快 def prime(a):

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

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

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

if str(i)==str(i)[::-1] and prime(i):
    print(i)

|