#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;
#define rep(i, n) for (ll i = 0; i < (ll)(n); ++i)
#define rep2(i, s, n) for (ll i = (s); i < (ll)(n); i++)
const ll MAX = 1001001;
const ll MOD = 1000000007;
const long double pi = 2.0 * asin(1.0);
ll dx[4] = {1, 0, -1, 0};
ll dy[4] = {0, 1, 0, -1};
ll modpow(ll a, ll n, ll mod)
{
    ll res = 1;
    while (n > 0)
    {
        if (n & 1)
            res = res * a % mod;
        a = a % mod * (a % mod) % mod;
        n >>= 1;
    }
    return res;
}
int main()
{
    ll n, p;
    cin >> n >> p;
    ll ans = (p - 1) * modpow(p - 2, n - 1, MOD) % MOD;
    cout << ans << endl;
}
#include <bits/stdc++.h>

using namespace std;

const int P = 1e9+7;

/*struct mat{
    int a[3][3];
    void start() {
        for (int i = 0; i < 2; ++i) {
            for (int j = 0; j < 2; ++j) {
                a[i][j] = 0;
            }
        }
        for (int i = 0; i < 2; ++i) {
            a[i][i] = 1;
        }
    }
} base;

mat mult(mat a, mat b) {
    mat res;
    res.start();
    for (int k = 0; k < 2; ++k) {
        for (int i = 0; i < 2; ++i) {
            for (int j = 0; j < 2; ++j) {
                res.a[i][j] += (a.a[i][k] * 1ll * b.a[k][j])%P;
                res.a[i][j] %= P;
            }
        }
    }
    return res;
};

mat fpow(mat a, int k) {
    mat res;
    res.start();
    for (;k; k>>=1, a = mult(a, a)) {
        if(k&1) {
            res = mult(res, a);
        }
    }
    return res;
}




int main() {
    long long n, p;
    cin >> n >> p;
    base.a[0][0] = p;
    base.a[0][1] = 0;
    base.a[1][0] = p-1;
    base.a[1][1] = 1;

    mat ans = fpow(base, n-1);

    cout << (3ll*ans.a[1][0])%P << endl;
}*/

int fpow(int a, int k) {
    int res = 1;
    for (;k; k>>=1, a = a * 1ll * a % P) {
        if(k&1) {
            res = res * 1ll * a % P;
        }
    }
    return res;
}

int main() {
    long long n, p;
    cin >> n >> p;
    if(p==2) {
        if(n == 1) cout << 1 << endl;
        else cout << 0 << endl;
    } else {
        int ans = fpow((p-2), n-1);
        cout << ((p-1) * 1ll * ans) % P << endl;
    }
}