#include<iostream>
#include<math.h>
#include<stdlib.h>
#include<string>
#include<limits.h>
#include<utility>
#include<vector>
//#include<bits/stdc++.h>
#include<tuple>
#include<queue>
#include<map>
#include<algorithm>
//#include <bits/stdc++.h>


#define rep(i,n) for(ll i=0;i<n;i++)
#define ALL(A) A.begin(),A.end()

using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;

const int MAX = 510000;
const int MOD = 1000000007;

long long fac[MAX], finv[MAX], inv[MAX];

// �e�[�u�������O����
void COMinit() {
	fac[0] = fac[1] = 1;
	finv[0] = finv[1] = 1;
	inv[1] = 1;
	for (int i = 2; i < MAX; i++) {
		fac[i] = fac[i - 1] * i % MOD;
		inv[i] = MOD - inv[MOD % i] * (MOD / i) % MOD;
		finv[i] = finv[i - 1] * inv[i] % MOD;
	}
}

// �񍀌W���v�Z
long long COM(int n, int k) {
	if (n < k) return 0;
	if (n < 0 || k < 0) return 0;
	return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;
}


int main() {
	ll n,p;
	cin>>n>>p;
	vector<ll> a(0);
	ll n1=n-1;
	while(n1>0){
		a.push_back(n1%2);
		n1/=2;		
	}
	ll tmp=a.size();
	//rep(i,tmp)cout<<a[i]<<" ";
	//cout<<endl;
	ll ans=p-1;
	ll mod=1e9+7;
	ll x=p-2;
	rep(i,tmp){
		if(a[i]==1){
			ans*=x;
		}
		ans%=mod;
		x*=x;
		x%=mod;
	}
	cout<<ans<<endl;
}
#include <bits/stdc++.h>


using ll = long long int;

ll mod_pow(ll n, ll r, ll mod) {
    ll ans = 1;
    ll pow = n;
    while (r > 0) {
        if (r & 1) {
            ans = (ans * pow) % mod;
        }
        pow = (pow * pow) % mod;
        r >>= 1;
    }
    return ans;
}

int main() {
    ll MOD = 1e9 + 7;
    ll N, P;
    std::cin >> N >> P;

    ll ans = (P - 1) * mod_pow(P - 2, N - 1, MOD) % MOD;
    std::cout << ans << std::endl;
}
