#include <bits/stdc++.h>
using namespace std;
struct vec {
  long long a[30];
};
struct mat {
  long long a[30][30];
};
long long n, k;
int val(long long um) {
  if (um < k) return um;
  return (um + val(um / k)) % k;
}
mat M[30], MI[30];
mat E[200][40], EI[200][40];
vec cur;
mat mult(mat m1, mat m2) {
  mat m3;
  for (int i = 0; i < k; i++) {
    for (int j = 0; j < k; j++) {
      m3.a[i][j] = 0;
      for (int l = 0; l < k; l++) {
        m3.a[i][j] += (m1.a[i][l] * m2.a[l][j]) % 1000000007LL;
      }
      m3.a[i][j] %= 1000000007LL;
    }
  }
  return m3;
}
vec mult(mat m, vec v) {
  vec v2;
  for (int i = 0; i < k; i++) {
    v2.a[i] = 0;
    for (int j = 0; j < k; j++) {
      v2.a[i] += (v.a[j] * m.a[i][j]) % 1000000007LL;
    }
    v2.a[i] %= 1000000007LL;
  }
  return v2;
}
void pre_comp() {
  for (int i = 0; i < k; i++) {
    E[0][i] = M[i];
    EI[0][i] = MI[i];
  }
  int LOG = 0;
  long long t = n;
  while (t > 0) {
    LOG++;
    t /= k;
  }
  for (int j = 1; j <= LOG; j++) {
    E[j][0] = E[j - 1][0];
    EI[j][0] = EI[j - 1][0];
    for (int l = 1; l < k; l++) {
      E[j][0] = mult(E[j - 1][l], E[j][0]);
      EI[j][0] = mult(EI[j][0], EI[j - 1][l]);
    }
    for (int i = 1; i < k; i++) {
      E[j][i] = mult(E[j - 1][i - 1], mult(E[j][i - 1], EI[j - 1][i - 1]));
      EI[j][i] = mult(E[j - 1][i - 1], mult(EI[j][i - 1], EI[j - 1][i - 1]));
    }
  }
}
vec solve(long long n, vec v, int at) {
  if (n == 0) return v;
  int w = val(n / k);
  v = solve(n / k, v, at + 1);
  for (int i = 0; i < n % k; i++) {
    v = mult(E[at][(w + i) % k], v);
  }
  return v;
}
int main() {
  scanf("%lld %lld", &n, &k);
  for (int i = 0; i < k; i++) {
    cur.a[i] = 1;
    for (int j = 0; j < k; j++) {
      for (int l = 0; l < k; l++) {
        if (j == l) {
          M[i].a[j][l] = 1;
          MI[i].a[j][l] = 1;
        } else if (j == i) {
          M[i].a[j][l] = 1;
          MI[i].a[j][l] = -1;
        } else {
          M[i].a[j][l] = 0;
          MI[i].a[j][l] = 0;
        }
      }
    }
  }
  pre_comp();
  cur = solve(n, cur, 0);
  long long tot = 0;
  for (int i = 0; i < k; i++) {
    tot += cur.a[i];
  }
  tot--;
  tot %= 1000000007LL;
  if (tot < 0) tot += 1000000007LL;
  while (tot % (k - 1) != 0) {
    tot += 1000000007LL;
  }
  printf("%lld\n", tot / (k - 1));
}
