I have tried all the boundary conditions, still I am getting wrong answer. I would really appreciate if someone could point out the error.
Try long long instead of long, maximal answer may be quite big.
And also all submissions for this problem are available, so you can compare any of them with your code (and also compare their output for any test with your output).
Long was working fine on my system. But turns out it was giving overflow here. Changing to long long corrected it.