Hello all,

I tried to optimize my code by using the method of Sieve of Eratosthenes. Despite that, I am getting the error of Time Limit Exceeded. Can someone help me understand, what’s the issue?

def sieveMethodOfPrimes(m,n):
    primeArr = [True for i in range(n+1)]
    primeArr[0], primeArr[1] = False, False

    p = 2
    while(p * p <= n):
	if(primeArr[p] == True):
		for x in range(p * p, n + 1, p):
			primeArr[x] = False
	p += 1

    for no in range(m,n+1):
 	    if primeArr[no]:
	 	    print(no)

t = int(input())
for testCases in range(t):
     m,n = [int(x) for x in input().split()]
     sieveMethodOfPrimes(m,n)
     print()
  • created

    Mar '22
  • last reply

    Mar '22
  • 1

    reply

  • 784

    views

  • 2

    users

No simple sieve will be quick enough, even in a fast language. I doubt it will even be able to allocate enough memory for the primeArr when n is 1000000000.

You’ll need to come up with a better algorithm. Try searching this forum for some ideas.