#include <bits/stdc++.h>
using namespace std;
int bio[1000005];
vector<int> g[1000005];
int k, p;
void dfs(int x) {
  if (bio[x]) return;
  bio[x] = 1;
  dfs((1LL * x * k) % p);
}
int main() {
  cin >> p >> k;
  int res = 1;
  for (int i = 1; i < p; i++) {
    if (!bio[i]) dfs(i), res = (1LL * res * p) % 1000000007;
  }
  if (k == 1) res = (res * 1LL * p) % 1000000007;
  cout << res;
  return 0;
}
