0

I have a problem with my code, I use the eratosthenes this function to create a list, and I just make a big memory size list (1000000), in the main I input the codeforces input() and let them sqrt(), so, I dont know why my code timelimit over than 2000ms, please help me to solve this problem.

import math

def eratosthenes(n):  # creative the prime list
    IsPrime = [True] * (n + 1)
    IsPrime[1] = False
    for i in range(2, int(n ** 0.5) + 1):
        if IsPrime[i]:
            for j in range(i * i, n + 1, i):
                IsPrime[j] = False
    return [x for x in range(2, n + 1) if IsPrime[x]]

#  main code
input()
li = list(map(int, input().split()))
nl = eratosthenes(1000000)
for i in li:
    i = math.sqrt(i)
    if int(i) == i:
        print("YES" if i in nl else "NO")
    else:
        print("NO")

I think the run time of my code is similar to other's code when I refer them, or I'm wrong.

Daniel kuo
  • 43
  • 1
  • 9
  • Why is `return [x for x in range(2, n + 1) if IsPrime[x]]` indented? This will return after the first number? Should this be outside the for loop? – Max Sep 06 '18 at 14:36
  • How are you satisfying the input()? Is this just waiting for a user to type a number, or is the input provided on stdin? – Max Sep 06 '18 at 14:37
  • Your first munber is 0 or 2 ? it return just like [2, 3, 5, 7, 11.....] – Daniel kuo Sep 07 '18 at 03:42
  • I do it on the codeforces and them will give me some input() [link](http://codeforces.com/problemset/problem/230/B) – Daniel kuo Sep 07 '18 at 03:44
  • It's a bit hard to say how your actual code looks like because the indentation is broken in the question. Could you correct that please? I see two instances of unnecessary work: creating the list from `IsPrime` and then doing a linear search in that list. For testing if a number is prime, the `IsPrime` list itself can already be used. – BlackJack Sep 19 '18 at 16:21

1 Answers1

0

I think your eratosthenes function is OK, the main bottleneck is when you are answering the questions...

print("YES" if i in nl else "NO")

in this part you search in nl list and this is O(p) where p is the number of prime numbers in nl. number of primes less then N is O(N/logN), in particular here around 78500 numbers.

so if the input consists of some big square, but not T-prime numbers, your code will do around 10^5 * 78500 ~= 8*10^9 operations, which makes TimeLimitError.

you can use your IsPrime array to check if the number is prime.

besides this to speed up, I don't know how fast python sqrt is, but you can calculate sqrt with binary search and see if it's better.

AMJ
  • 1