#include <bits/stdc++.h>
using namespace std;

#define MOD 1000000007

long long pows(long long a, long long b) {
  if (a == 0) return 0;
  long long left = b;
  long long ks = a;
  long long ans = 1;
  while (left > 0) {
    if (left%2 == 1) {
      ans = ans*ks%MOD;
    }
    ks = ks*ks%MOD;
    left /= 2;
  }
  return ans;
}

int main() {
  
  ios::sync_with_stdio(false);
  cin.tie(0);
  long long n,p;
  cin >> n >> p;
  long long ans = p-1;
  ans *= pows(p-2,n-1);
  ans %= MOD;
  if (n == 1 && p == 2) ans = 1;
  cout << ans << endl;
}
#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<b;i++)
#define rrep(i,a,b) for(int i=a;i>=b;i--)
#define fore(i,a) for(auto &i:a)
#define all(x) (x).begin(),(x).end()
//#pragma GCC optimize ("-O3")
using namespace std;
void _main(); int main() { cin.tie(0); ios::sync_with_stdio(false); _main(); }
typedef long long ll; const int inf = INT_MAX / 2; const ll infl = 1LL << 60;
template<class T>bool chmax(T& a, const T& b) { if (a < b) { a = b; return 1; } return 0; }
template<class T>bool chmin(T& a, const T& b) { if (b < a) { a = b; return 1; } return 0; }
//---------------------------------------------------------------------------------------------------
/*---------------------------------------------------------------------------------------------------
　　　　　　　　　　　 ∧＿∧
　　　　　 ∧＿∧ 　（´<_｀ ）　 Welcome to My Coding Space!
　　　　 （ ´_ゝ`）　/　 ⌒i     @hamayanhamayan0
　　　　／　　　＼　 　  |　|
　　　 /　　 /￣￣￣￣/　　|
　 ＿_(__ﾆつ/　    ＿/ .| .|＿＿＿＿
　 　　　＼/＿＿＿＿/　（u　⊃
---------------------------------------------------------------------------------------------------*/














string X; ll M;
//---------------------------------------------------------------------------------------------------
bool check(ll n) {
	vector<ll> Y;
	ll m = M;
	while (0 < m) {
		Y.push_back(m % n);
		m /= n;
	}
	reverse(all(Y));

	if (X.size() < Y.size()) return true;
	else if (X.size() > Y.size()) return false;
	
	// the same size.
	int len = X.size();
	rep(i, 0, len) {
		ll x = X[i] - '0';
		ll y = Y[i];

		if (x == y) continue;
		else if (x < y) return true;
		else return false;
	}

	// X == Y
	return true;
}
//---------------------------------------------------------------------------------------------------
void _main() {
	cin >> X >> M;

	if (X.length() == 1) {
		ll x = stoll(X);
		cout << (x <= M ? "1" : "0") << endl;
		return;
	}

	int ma = -1;
	fore(c, X) chmax(ma, c - '0');

	ll ok = ma, ng = infl;
	while (ok + 1 < ng) {
		ll md = (ok + ng) / 2;
		if (check(md)) ok = md;
		else ng = md;
	}

	ll ans = ok - ma;
	cout << ans << endl;
}





