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


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.

Program to illustrate the working of our solution,

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

Updated on: 25-Jan-2021

133 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements