#include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
const int nmax = 1e6;
long long binpow(long long a, long long b) {
  long long res = 1;
  while (b) {
    if (b & 1) res = res * a % mod;
    a = a * a % mod;
    b >>= 1;
  }
  return res;
}
long long p, k;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0), cout.tie(0);
  cin >> p >> k;
  long long ord = 1;
  long long cur = k;
  if (k == 0) {
    cout << binpow(p, (p - 1));
    return 0;
  }
  if (k == 1) {
    cout << binpow(p, p);
    return 0;
  }
  while (cur != 1) {
    cur = cur * 1ll * k % p;
    ord++;
  }
  long long ans = binpow(p, (p - 1) / ord);
  ans %= mod;
  cout << ans;
}
