#include <bits/stdc++.h>
using namespace std;
signed long long P, K;
signed long long mo = 1000000007;
template <int um>
class UF {
 public:
  vector<int> par, rank;
  UF() {
    rank = vector<int>(um, 0);
    for (int i = 0; i < um; i++) par.push_back(i);
  }
  int operator[](int x) {
    return (par[x] == x) ? (x) : (par[x] = operator[](par[x]));
  }
  int operator()(int x, int y) {
    if ((x = operator[](x)) == (y = operator[](y))) return x;
    if (rank[x] > rank[y]) return par[x] = y;
    rank[x] += rank[x] == rank[y];
    return par[y] = x;
  }
};
UF<1000002> uf;
void solve() {
  int i, j, k, l, r, x, y;
  string s;
  cin >> P >> K;
  signed long long ret = 1;
  if (K == 0) {
    for (i = 1; i < P; i++) ret = ret * P % mo;
  } else if (K == 1) {
    for (i = 0; i < P; i++) ret = ret * P % mo;
  } else {
    for (i = 1; i < P; i++) uf(i, (i * K) % P);
    for (i = 1; i < P; i++)
      if (uf[i] == i) ret = ret * P % mo;
  }
  cout << ret << endl;
}
int main(int argc, char** argv) {
  string s;
  int i;
  if (argc == 1) ios::sync_with_stdio(false);
  for (i = 0; i < argc - 1; i++) s += argv[i + 1], s += '\n';
  for (i = 0; i < s.size(); i++) ungetc(s[s.size() - 1 - i], stdin);
  solve();
  return 0;
}
