#include<bits/stdc++.h>
using namespace std;
long long n,p,ans,bs;
long long MOD=1000000007;
int main()
{
	cin>>n>>p;
	if(p==2)
	{
		if(n==1)cout<<"1";
		else cout<<"0";
	}
	else if(p==3)cout<<"2";
	else
	{
		ans=(p-1)%MOD;
		bs=(p-2)%MOD;
		n--;
		while(n)
		{
			if(n&1==1)ans=(ans*bs)%MOD;
			bs=(bs*bs)%MOD;
			n>>=1;
		}
		cout<<ans%MOD;
	}
    return 0;
}
#include <bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>

#define x first
#define y second
#define ndl '\n'
#define mp make_pair
#define mt make_tuple
#define pb push_back
#define up_b upper_bound
#define low_b lower_bound
#define sz(x) (int)x.size()
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()

using namespace std;
//using namespace __gnu_pbds;

//template<typename T> using indexed_set = tree <T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());//uniform_int_distribution<int> (l, r)

typedef long long ll;
typedef long double ld;
typedef unsigned int uint;
typedef unsigned long long ull;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
typedef pair<int, ll> pil;
typedef pair<ll, int> pli;
typedef pair<int, ull> piu;
typedef vector<vector<int>> matrix;

const ll INF = 1e18 + 123;
const ld EPS = 1e-9;
const int inf = 1e9 + 123;
const int MOD = 1e9 + 7;
const int N = 1e5 + 123;
const int M = 1e6 + 123;
const double pi = 3.14159265359;
const int dx[] = {0, 0, 1, -1};
const int dy[] = {1, -1, 0, 0};

int binpow(int a, int b){
    int res = 1;
    while (b){
        if (b&1) res = 1ll*res*a % MOD;
        b >>= 1;
        a = 1ll*a*a % MOD;
    }
    return res;
}

void solve(){
    int n, p;
    cin >> n >> p;
    cout << 1ll*(p-1)*binpow(p-2, n-1) % MOD;

}

int main(){
    #ifndef ONLINE_JUDGE
        freopen("input.txt", "r", stdin);
        freopen("output.txt", "w", stdout);
    #endif
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int t = 1;  
    //cin >> t;
    for (int i = 1; i <= t; i++){
        //cout << "Case #" << i << ": ";
        solve();
    }
    #ifdef KAZAKH
      //  cout << endl << 1.0 * clock() / CLOCKS_PER_SEC << endl;
    #endif
    return 0;
}