#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
long long add(long long a, long long b) { return (a + b) % MOD; }
long long mul(long long a, long long b) { return (a * b) % MOD; }
long long binpow(long long a, long long b) {
  long long res = 1;
  while (b) {
    if (b & 1) {
      res = mul(res, a);
    }
    a = mul(a, a);
    b >>= 1;
  }
  return res;
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  long long p, k;
  cin >> p >> k;
  if (k == 0) {
    cout << binpow(p, p - 1) << endl;
    return 0;
  }
  vector<long long> used(p);
  long long cnt = 0;
  for (long long i = 1; i < p; i++) {
    if (!used[i]) {
      long long cur = i;
      while (!used[cur]) {
        used[cur] = 1;
        cur *= k;
        cur %= p;
      }
      cnt++;
    }
  }
  if (k == 1) cnt++;
  cout << binpow(p, cnt) << endl;
}
