Reverse Maximisation (Edge Case Help)

https://www.codechef.com/viewsolution/24412266

i am having problem with test cases like when N = 10128 , N = 10199 , N = 10007
i am getting right answer for 10199 and 10007 but wrong for 10128.
What should be my logic so that these cases are handled.