CODEMANIA PROBLEM "CUPID ME"

above is the problem
here i am not able to think what to do other than finding primes in the given range
Please help
Thanks

Thanks man.
I got a idea ,to go further.
Did you also solve problem CodeChef: Practical coding for everyone .
from same contest ,I am just able to think about brute force solution .how can optimise ?
Thanks in advance

Can someone help me understand what’s wrong with this submission of mine?

https://www.codechef.com/viewsolution/29236202

Question link : CodeChef: Practical coding for everyone

Link to a similar solution that got AC: CodeChef: Practical coding for everyone

Hey, can you explain, how the expected value is

N + Q - N/(Q+1)