By going through your code, what I understood that is that you didn’t get the problem actually or maybe you failed to implement your idea correctly. Just for clarity, the problem asks for the next number greater than or equal to n, which is prime and lies in the range l to r. But what you have actually done in your code is that, you first found out the next prime number to n and then checked for something. No, you don’t need to find just the next prime to n, you need to find the next prime to n which lies in the range of l to r.

Since the given range of l to r is <= 1e5, you can use array to store all the prime numbers from l to r. Then you can use a dictionary to store the next prime numbers of the numbers in the range l to r, because the number between l and r are our concern. If n < l, then you simply need to print the next prime to l if it exists or print -1. If n > r or there is no prime number in after n which is < r, then simply print -1, otherwise you can find the prime number next to n within the given range of l to r from the dictionary in O(1) time, which is necessary for the large volume of queries.

You can find my solution if it help.

Hope this clears your doubt about the solution. Feel free to ask if you have any more doubts.