Cho N, tìm X sao cho X + sum_digits(X) = N. Vì sum_digits(X) ≤ 9×10 = 90 (với N ≤ 1e9), X chỉ cách N tối đa 100. Duyệt từ N-100 đến N+100 kiểm tra.
Ví dụ mã nguồn
#include <bits/stdc++.h>
using namespace std;
int digitSum(int n) {
int s = 0;
while (n) { s += n%10; n/=10; }
return s;
}
void findX(long N) {
bool found = false;
for (int i=0;i<=100;i++) {
long L = abs(N - i);
if (L + digitSum(L) == N) { cout << L << ' '; found = true; }
long R = N + i;
if (R + digitSum(R) == N) { cout << R << ' '; found = true; }
}
if (!found) cout << "Khong tim thay";
cout << endl;
}
int main() {
findX(89); // 76 (76+7+6=89)
return 0;
}
Kết quả
76
76 + 7 + 6 = 89.