Constraints of this question are very high. later i got to know we can obtain answer in O(1) by using some formulae =(2nk-2n+2)/k;

but i did not get this . can anybody explain me this formulae ?

Sorry, I put the wrong link.

Here is correct question

Please help me

Where did you find this formula? What is k here?

If you want to see the solution explained, the problem does have an editorial but it seems to be not linked to the problem.