Find kth smallest number in range [1, n] when all the odd numbers are deleted in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two integer values n and k. Our task is to find kth smallest number in range [1, n] when all the odd numbers are deleted.

We need to find the kth smallest number in the range [1, n] which contains only even values.

So, from range [1, 5] -> number will be 2, 4.

Let’s take an example to understand the problem,

Input: n = 12, k = 4

Output: 8

Explanation:

Even elements in the range [1, n] : 2, 4, 6, 8, 10, 12

The 4th smallest element is 8.

Solution approach:

The solution is simple as we need to find the kth element from even numbers upto n. This can be easily calculated using the formula,

Element = 2*k.

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;

int main() {

int n = 124, k = 12;
if(n > 2*k){
cout<<"kth smallest number is "<<(2 * k);
}
else
cout<<"kth smallest number cannot be found";
return 0;
}

Output

kth smallest number is 24
Published on 25-Jan-2021 04:52:08