6 / 6
Jul 2017

from math import sqrt
from collections import deque
t=int(input("enter the test cases"))
if t>10:
    print("enter the values under 10")
else:
    q=deque([])
    q1=deque([])
    for i in range(0,t):
        m,n=input().split()
        m=int(m)
        n=int(n)
        q.append(m)
        q1.append(n)
    while t != 0:
        m1 = q.popleft()
        n1 = q1.popleft()
        if 1 <= m1 <= n1 <= 1000000000 and n1 - m1 <= 100000:
            for num in range(m1,n1):
                def is_prime(k):
                    if k == 2:
                        return True
                    if k % 2 == 0 or k <= 1:
                        return False
                    sqr = int(sqrt(k)) + 1
                    for divisor in range(3, sqr, 2):
                        if k % divisor == 0:
                            return False
                    return True
                if is_prime(num):
                    print(num)
        print("\n")
        t-=1

i am getting a time exceeded in this code please anyone suggest a way to optimize the code

  • created

    Mar '17
  • last reply

    Jul '17
  • 5

    replies

  • 1.1k

    views

  • 3

    users

You should move your is_prime-Function outside of your loop, e.g. directly under the import statements. There is no need to redefine the function for each and every number in the range.

And you should avoid to prompt any text when reading input. The text “enter the test cases” will be evaluated as output of your program which will result in “wrong answer”.

There is no need to store the m, n values in any structure. You can simply do this:

t = int(input())
for _ in range(t):
    m, n = input().split()
    m, n = int(m), int(n)
    for num in range(m, n+1):
        #do something

But this will not speed up your code too much. There are at max ten test only cases, queueing will not consume much of the runtime....

please show your updated code.

4 months later

I am facing same problem .....

def isPrime( num):

if num > 2:
    for i in range( 2, num):
        if (num % i) == 0:
            return 0
    return 1
elif num == 1:
    return 0
elif num == 2:
    return 1
else :
    return 1

def primegen( low, high):

for i in range( low, high + 1):
    if isPrime(i):
        print ( i)
print('')

def main():

n = int(input())
if n!= 0:
    #rangeMat = [[0 for x in range(2)] for y in range(n)]

    #for i in range(n):
    #    rangeMat[i][0], rangeMat[i][1] = map(int, input().split())
    #    primegen( rangeMat[i][0], rangeMat[i][1])

    for i in range(n):
        a, b = map(int, input().split())
        primegen( a, b)

else:
    return

main()