Whats Wrong with my code in HMAPPY2

Can somebody tell me what is wrong with my code for the problem HMAPPY2 in FEB19? I am really not able to figure out why its showing wrong answer. Please help! My code is as shown below :

http://cpp.sh/3d4n2

All it has to do is with constraints if you look at constraints n <= 10^18 and time provided is 1 sec. So you cannot perform linear traversing. Try to solve it mathematically, if after a lot of tries you cannot solve take a look at my code(Python) - https://www.codechef.com/viewsolution/22736696
c++ code: https://www.codechef.com/viewsolution/23092184

//