ให้จำนวนเต็มบวกสองจำนวน n และ k และเราต้องหาจำนวนที่ n ที่มีหลัก k หรือหารด้วย k ลงตัว k จะอยู่ในช่วง [2 ถึง 9] ดังนั้น ถ้า n และ k เป็น 15 และ 3 ตามลำดับ ผลลัพธ์ที่ได้คือ 33 ดังตัวเลข [3, 6, 9, 12, 13, 15, 18, 21, 23, 24, 27, 30, 31, 33] เหล่านี้คือ ตัวเลขที่แต่ละองค์ประกอบมีตัวเลข k =3 หรือการหารด้วย k และในจำนวนที่ n นี้คือ 33 ดังนั้นผลลัพธ์คือ 33
ตรวจสอบแต่ละตัวเลขที่มี k และตัวคูณของ k แล้วนับจนได้องค์ประกอบที่ n
ตัวอย่าง
#include<iostream>
using namespace std;
bool hasDigit(int n, int k) {
while (n > 0) {
int rem = n % 10;
if (rem == k)
return true;
n = n / 10;
}
return false;
}
int countNumbers(int n, int k) {
for (int i = k + 1, count = 1; count < n; i++) {
if (hasDigit(i, k) || (i % k == 0))
count++;
if (count == n)
return i;
}
return -1;
}
int main() {
int n = 10, k = 2;
cout << "Last number is " << countNumbers(n, k) << " before that the number contains " << k << " and multiple of " << k;
} ผลลัพธ์
Last number is 20 before that the number contains 2 and multiple of 2