#include <bits/stdc++.h>
using namespace std;
const int N = 100 * 10000 + 5;
vector<int> v[N];
vector<bool> vis(N, false);
long long power(long long a, long long b, long long c) {
  long long res = 1;
  while (b != 0) {
    if (b & 1) res = (res * a) % c;
    a = (a * a) % c;
    b /= 2;
  }
  return res;
}
void dfs(int s) {
  vis[s] = 1;
  for (auto g : v[s]) {
    if (!vis[g]) dfs(g);
  }
}
int main() {
  long long p, k;
  cin >> p >> k;
  for (int i = 1; i < p; i++) {
    v[i].push_back((k * i) % p);
  }
  if (k == 1) {
    cout << power(p, p, 1000000007);
    return 0;
  }
  int cc = 0;
  for (int i = 1; i < p; i++) {
    if (!vis[i]) {
      dfs(i);
      cc++;
    }
  }
  cout << power(p, cc, 1000000007);
}
