#include <bits/stdc++.h>
using namespace std;
const int64_t mod = 1e9 + 7;
int64_t bpow(int64_t x, int64_t n, int64_t m) {
  if (n == 0) return 1;
  int64_t t = bpow(x, n / 2, m);
  if (n % 2 == 1)
    return x * t % m * t % m;
  else
    return t * t % m;
}
signed main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int64_t p, k;
  cin >> p >> k;
  if (k == 1) {
    cout << bpow(p, p, mod) << "\n";
    return 0;
  }
  if (k == 0) {
    cout << bpow(p, p - 1, mod) << "\n";
    return 0;
  }
  for (int64_t i = 1; i < p; i++) {
    if (bpow(k, i, p) == 1) {
      cout << bpow(p, (p - 1) / i, mod) << "\n";
      return 0;
    }
  }
  return 0;
}
