1 / 4
Jul 2022

i am getting correct ans but getting tle…please help me reduce the time…

import math
n=int(input())
a=[[]]
flag=0
for i in range(n):
    b=list(map(int,input().split()))
    if(b[1]>b[0] and b[1]<=1000000000 and b[0]<=1000000000  and b[1]-b[0]<=100000 and 1<=b[1] and 1<=b[0]):
        a.append(b)
    else:
        print("the nos entered are wrong")
        b=0
        break
print("\n")


for w in range(1,n+1,1):
    x=a[w][0]
    y=a[w][1]
    l=int(math.sqrt(y))
    prime=[]
    primes=[]
    q=0
    if(x%2==0):
        if(x==2):
            x=x+1
        if(x>2):
            x=x+1
        
    else:
        if(x==1):
            x=x+2
            
   for i in range(3,l+2,2):
        prime.append(1)
   t=x
    if(l%2==0):
        l=l-1
    t=3
    for k in range(3,l+2,2):
        if(prime[k-t]==1):
            s=k
            primes.append(k)
            if((k*k)<=l):
                for j in range(k*k,l+1,2*k):
                    d=int((j-k)/2+t)
                    prime[j-d]=0
        t=t+1
    u=len(primes)
    prime=[]
    for b in range(x,y+1,2):
        prime.append(1)
    t=x
    for g in range(x,y+1,2):
            for o in range(u):
                if((g%primes[o])==0):
                    prime[g-t]=0
                    break
             t=t+1
    t=x
    for j in range(x,y+1,2):
        if(prime[j-t]==1):
            if(j>1):
                print(j) 
        t=t+1
    w=w+1
    print("\n")

‘’’

  • created

    Jul '22
  • last reply

    Jul '22
  • 3

    replies

  • 620

    views

  • 2

    users

  • 1

    link

If you want people to read your code then you have to make it readable - and that includes retaining the indentation when posted here. This last point is especially important with Python of course.

Please edit your post and put three back ticks ``` on a line by themselves both before and after the code. This will then retain the formatting and indentation.

I’m curious though, if you run it on IDEONE, how long does it take to process this test case?

1
999900000 1000000000

PRIME13

I think it may be a struggle to solve this with Python. There are already many solvers, including from after the compiler and time-limit change, so it’s not impossible.

I don’t know much about Python, so I might be talking rubbish, but here goes…

The code adds an awful lot of numbers to lists - that’s got to take some time right? Can you pre-allocate the space for the full list rather then increase it incrementally? You re-sieve the Prime array for each test case, but the primes aren’t going to change - create the list once with the maximum size needed for these test cases and then re-use it.

The comments suggest this may be one of the cases where trial division is better than trying to sieve btw, but ymmv.

(Once you get past the TLE, I expect you’ll get WA, but that’s a question for another day.)