Please help me in problem NUKES

I am facing problem with this question:

My solution is:

I am getting time limit exceeded, only in case 5, 6 ,7. All other cases are being excepted.
I tried optimizing the code by adding a while loop, but yet no effect.
Please help.

I read your code but can’t understand too much as I don’t know that language.
However I solved the question. What I understand from question is
if we insert A particles then A%(n+1) will remain in 0th chamber and A/(n+1) will go in next. the same will repeat for next also. now A=a/(n+1);
A%(n+1) will remain in 1st chamber and A/(n+1) will go in next, now A=a/(n+1); so on…
my solution is in java