#include <bits/stdc++.h>
using namespace std;
signed long long P, K;
signed long long mo = 1000000007;
void solve() {
  int i, j, k, l, r, x, y;
  string s;
  cin >> P >> K;
  signed long long ret = 1;
  if (K <= 1) {
    for (i = 0; i < P - (K == 0); i++) ret = ret * P % mo;
  } else {
    signed long long cur = 1;
    for (i = 1; i < P; i++) {
      cur = cur * K % P;
      if (cur == 1) break;
    }
    for (x = 0; x < (P - 1) / i; x++) 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;
}
