Cant find any other method than brute force

For the problem Prime visits I have written a code using brute force and it is giving me a time error, I cannot find any other approach to solve this, please help.

Aryann, You have to use prime seive optimisation in your code…Pls refer to this online video of prateek bhaiya…