1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>

using namespace std;

const int mod = 1e9 + 7;
long long n, m;

long long fastPot(long long pod, long long wyk)
{
	if (wyk == 2)
		return (pod * pod) % mod;
	else if (wyk == 1)
		return pod % mod;
	else if (wyk == 0)
		return 1;
	
	return (fastPot(fastPot(pod, wyk / 2) % mod, 2) % mod) * (fastPot(pod, wyk % 2) % mod) % mod;
}
int main()
{
	cin >> n >> m;
	if (n == 1)
	{
		cout << 0;
		return 0;
	}
	long long wyn = 0;
	wyn += fastPot(m, n - 1);
	for (int i = 2; i <= n - 2; i++)
	{
		int chwWyn = fastPot(m, n - 2) - fastPot(m, n - 3);
		chwWyn %= mod;
		wyn += chwWyn;
		wyn %= mod;
	}
	cout << wyn;

	return 0;
}