Please help me optimize my code for MAANDI..

Hello guys,
Please help me optimize my code for MAANDI…Currently,when I run this code on my system, it displays correct answers in a fraction of second (even for very large numbers)…But on Codechef, it is showing “Time Limit Exceeded”.
Any general advice is also appreciated…(new to coding):wink:
Thanks…

(Link to Solution removed due to comment below)

remove this post.You are not allowed to ask hints during an active contest.

ok…will keep that in mind in future…

You will get all advice and help but only after the contest. keep trying till then.