It shows time limit error. what else can be a more efficient way.also for one case it shows that the answer is wrong. i am not able to figure out which case is likely to yield a wrong answer

You have to use Sieve of Eratosthenes for primes in this problem. The test cases are large and so without this it will give TLE. Lecture video of Sieve of Eratosthenes is there in the Number Theory section of your course. Please refer that first and then try to solve this problem using that concept.

You can refer this: