#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
const int maxn = 1e6 + 3000;
const long long mod = 1e9 + 7;
long long k, p;
int f[maxn];
bool vis[maxn];
long long cnt[maxn];
long long qpow(long long x, long long p) {
  long long ans = 1;
  while (p) {
    if (p & 1) ans = ans * x % mod;
    x = x * x % mod;
    p >>= 1;
  }
  return ans;
}
int main() {
  cin >> p >> k;
  if (k == 0) {
    cout << qpow(p, p - 1) << endl;
    return 0;
  }
  if (k == 1) {
    cout << qpow(p, p) << endl;
    return 0;
  }
  for (int i = 1; i < p; i++) {
    f[i] = i * k % p;
  }
  long long ans = 1;
  for (int i = 1; i < p; i++) {
    int c = 0;
    if (vis[i]) continue;
    int x = i;
    while (!vis[x]) {
      vis[x] = 1;
      x = f[x];
      c++;
    }
    cnt[c]++;
  }
  for (int i = 2; i < maxn; i++) {
    if (cnt[i]) {
      ans = ans * qpow(i * cnt[i] + 1, cnt[i]) % mod;
    }
  }
  cout << ans << endl;
  return 0;
}
