Timilit Error in problem to find prime numbers between two numbers

The code seems fine but maybe its taking too much time t execute. It is running good in Jupyter notebook. What Changes can be done ?
Here is the code-

num = int(input())
mylist = []
for n in range(num):
[x,y] = list(map(int,input().split()))
mylist.append((x,y))

for (x,y) in mylist:
for num in range(x,y+1):

   if num > 1:
       for i in range(2, num):
           if (num % i) == 0:
               break
       else:
           print(num,end = " ")
print()

Hey @sanchit123manchanda,

Please save the code in the IDE and share the link here.


Here is the link
Run this in python

Your code is perfectly fine in terms of logic. The problem is the time complexity, you are using two loops which means time complexity for your algorithm will be O(n^2). As you can see we are given that the values of m and n can range:

  1. 1 <= m <= 10000000000
  2. 1 <= n <= 10000000000

Surely with such big values of m, n your code will show up TLE(Time limit exceeded).

Solution :
Try to solve the problem in O(n) using sieve of Eratosthenes.

I hope this helps :slight_smile:

I tried by that method. But its still showing error while the code looks fine.