You are not logged in. Please login at www.codechef.com to post your questions!

×

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;
}

asked 22 Jul '18, 17:17

montycs's gravatar image

0★montycs
1057
accept rate: 0%

edited 25 Jul '18, 21:15


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.

link

answered 25 Jul '18, 21:30

shashwat001's gravatar image

4★shashwat001
5241610
accept rate: 17%

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?

(25 Jul '18, 22:27) montycs0★
1

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.

(25 Jul '18, 23:43) shashwat0014★

Nice.. got it..

(26 Jul '18, 22:21) montycs0★
toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:

×688

question asked: 22 Jul '18, 17:17

question was seen: 181 times

last updated: 26 Jul '18, 22:21