#include <bits/stdc++.h>
int deg(int a, int n) {
  if (n == 0) {
    return 1;
  }
  int t = deg(a, n / 2);
  t = (long long)t * t % 1000000007;
  if (n % 2) {
    t = ((long long)t * a % 1000000007);
  }
  return t;
}
int f(int k, int p) {
  int ans = 1;
  for (int t = k; t != 1; t = ((long long)t * k % p)) {
    ++ans;
  }
  return ans;
}
using namespace std;
int main() {
  int p, k;
  cin >> p >> k;
  if (k == 0) {
    cout << deg(p, p - 1) << endl;
    return 0;
  }
  int m = f(k, p);
  int n = (p - 1) / m;
  if (k == 1) {
    ++n;
  }
  cout << deg(p, n) << endl;
  return 0;
}
