ในปัญหานี้เราจะพยายามหาเลข K หลักที่ใหญ่ที่สุด ที่จะหารด้วย X ลงตัว เพื่อทำงานนี้ เราจะ取เลข K หลักที่ใหญ่ที่สุดด้วยสูตร ((10^k) - 1) จากนั้นตรวจสอบว่าตัวเลขหารด้วย X ลงตัวหรือไม่ ถ้าไม่ เราจะได้ตัวเลขที่ถูกต้องโดยใช้สูตรนี้
max - (max mod X)
ตัวอย่างหนึ่ง คือ เลข 5 หลัก ที่หารด้วย 29 ลงตัว เลข 5 หลักที่ใหญ่ที่สุดคือ 99999 ไม่หารด้วย 29 ลงตัว ตอนนี้ใช้สูตรจะได้ −
99999 - (99999 mod 29) = 99999 - 7 = 99992
เลข 99992 หารด้วย 29 ลงตัว
อัลกอริทึม
maxKDigit(k, x)
begin
max = (10^k) - 1
if max is divisible by x, return max
otherwise return max - (max mod x)
end
ตัวอย่าง
#include<iostream>
#include<cmath>
using namespace std;
long max_k_digit(int k, int x) {
// get the maximum number of k digits
int max = pow(10, k) - 1;
if(max % x == 0) {
return max;
}
return (max) - (max % x);
}
int main() {
int k, x;
cout << "Enter Digit Count(K) and Divisor(N): ";
cin >> k >> x;
cout << "Result is: " << max_k_digit(k, x);
}
ผลลัพธ์
Enter Digit Count(K) and Divisor(N): 5 29 Result is: 99992
ผลลัพธ์เพิ่มเติม
Enter Digit Count(K) and Divisor(N): 6 87 Result is: 999978