Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

หาเลขที่ k-th น้อยที่สุดในช่วง [1, n] หลังลบเลขคี่ใน C++

โจทย์

ได้รับ n และ k ทางเราต้อง หาเลขที่ k-th น้อยที่สุดในช่วง [1, n] ที่เหลือเฉพาะเลขคู่

ตัวอย่าง

Input: n = 12, k = 4

Output: 8

อธิบาย: เลขคู่ใน [1,12]: 2,4,6,8,10,12 -> ตัวที่ 4 คือ 8

แนวทางแก้ปัญหา

เลขคู่ลำดับที่ k คือ 2*k (ตราบใดที่ 2*k ≤ n)

โปรแกรมตัวอย่าง

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

ผลลัพธ์

kth smallest number is 24