#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
long long p, k;
long long quick_pow(long long x, long long n) {
  long long ans = 1;
  while (n) {
    if (n & 1) ans = ans * x % mod;
    n >>= 1;
    x = x * x % mod;
  }
  return ans;
}
signed main() {
  cin >> p >> k;
  if (k == 0)
    cout << quick_pow(p, p - 1);
  else if (k == 1)
    cout << quick_pow(p, p);
  else {
    long long m = 1, x = k;
    while (x != 1) m++, x = x * k % p;
    cout << quick_pow(p, (p - 1) / m);
  }
  return 0;
}
