Logic review

Mr Pr in a Dilemma Problem Code: ICM2008 problem link:https://www.codechef.com/problems/ICM2008

my submission link: https://www.codechef.com/submit/ICM2008
My test case runs fine but after submission of my code , code show an error? Is my logic is rightor wrong?