the code is giving correct output, but tle error.
Time limit exceeded
When the number of test cases is less, your code is working fine.
The problem with your code is that for large number of test cases you are running the prime sieve again and again for each test case which is making the process inefficient and exceeding the time limit. So call the prime sieve function outside the loop for the test case.
Follow this approach:(I have commented out the steps)