Topics

Given two integers and , determine the number of positive integers () such that the difference between and the sum of its digits is at least . Formally, count all satisfying:

Idea

For a given , the function is non-decreasing. This means that once , all larger will also satisfy . Thus, the valid values form a contiguous range from some minimum valid (let’s call it ) to . We can use the binary search boolean array framework to efficiently find . The total valid numbers will then be: .

Binary Search Strategy:

  1. Search Space:
  2. Check Function: For a candidate , check if
  3. Monotonicity: Since is non-decreasing, binary search can find the smallest valid

Time Complexity: , where is the maximum number of digits in . Each binary search step checks the digits of .
Space Complexity: , constant extra space is used.

Proof of Monotonicity

We need to show that for all . Let’s compute the difference:

The term can be expressed as , where is the number of trailing 9s in . This is because incrementing turns trailing 9s into 0s (each reducing the sum by 9) and increments the next digit by 1. Thus:

Since , is non-decreasing.

Code

bool check(ll x, ll target) {
  ll sod = 0;
  while (x > 0) {
    sod += x % 10;
    x /= 10;
  }
  return sod <= target;
}
 
void solve() {
  ll n, s;
  cin >> n >> s;
 
  ll lo = 1;
  ll hi = n;
  ll ans = n+1;
 
  while (lo <= hi) {
    ll mid = lo + (hi - lo) / 2;
    if (check(mid, mid - s)) {
      ans = mid;
      hi = mid - 1;
    } else
      lo = mid + 1;
  }
 
  cout << (n - ans + 1) << endl;
}