Need help in understanding solution

I couldn’t solve this problem from codeforces: Even Odds so I looked online for solutions. I found one, I get the first part of if statement condition where we check the first half of the array but am unable to understand the else part condition… please help… here’s the solution:

#include <iostream>

using namespace std;

int main()
{
    long long n, k;
    cin >> n >> k;
    if (k <= (n + 1) / 2)
    {
        cout << k * 2 - 1 << endl;
    }
    else
    {
        cout << (k - (n + 1) / 2) * 2 << endl;
    }
    return 0;
}

There are (n+1)/2 odd numbers and remaining even numbers.
So if you remove first (n+1)/2 odds numbers from start, the remaining sequence will be like
2, 4, 6, 8, … i.e. twice of its position
So (k - (n + 1) / 2) * 2 does same only, removes all odds and then multiply by 2.

2 Likes

thanks a lot for your time… I know the solution is right since it is giving AC but why is (k - (n+1)/2) * 2… Fine, the *2 part is done since the values are double as compared to the index but why subtract number of odds from k? and why not from the entire length of numbers?

I think an example is required. Say n is 10 and k is 8. odd numbers are (n+1)/2 = 5. In the sequence, odd numbers are first followed by all even numbers. Now you need the 8th number in the sequence which is effectively 3rd number among even numbers. So you subtract 5 from 8.

1 Like

Nice… got it…