#include <bits/stdc++.h>
using namespace std;
long long power_mod(long long x, long long y, long long mod) {
  long long ret = 1;
  while (y) {
    if (y & 1) ret = (ret * x) % mod;
    x = (x * x) % mod;
    y >>= 1;
  }
  return ret;
}
long long baby_step_giant_step(long long x, long long y, long long z) {
  long long H = sqrt(z) + 1;
  set<pair<int, long long>> S;
  for (long long i = 0, w = y; i < H; i++, w = (w * x) % z) {
    S.insert({w, i});
  }
  long long k = -1;
  long long x_H = power_mod(x, H, z);
  for (long long i = 1, w = x_H; i <= H; i++, w = (w * x_H) % z) {
    auto itr = S.lower_bound({w + 1, 0});
    if (itr == S.begin()) continue;
    itr--;
    if (itr->first == w) {
      return H * i - itr->second;
    }
  }
  return k;
}
long long get_order(long long a, long long b) {
  return baby_step_giant_step(a, 1, b);
}
template <class T>
ostream& operator<<(ostream& os, vector<T> vec) {
  for (int i = 0; i < vec.size(); i++) {
    os << vec[i] << " ";
  }
  return os;
}
int main() {
  long long p, k;
  cin >> p >> k;
  if (k == 0) {
    long long ans = power_mod(p, p - 1, 1000000007);
    cout << ans << endl;
    return 0;
  } else if (k == 1) {
    long long ans = power_mod(p, p, 1000000007);
    cout << ans << endl;
    return 0;
  }
  long long len = get_order(k, p);
  assert(len != -1);
  long long d = (p - 1) / len;
  long long ans = 1;
  for (int i = 0; i < d; i++) {
    ans *= d * len + 1;
    ans %= 1000000007;
  }
  cout << ans << endl;
  return 0;
}
