#include <bits/stdc++.h>
using namespace std;
bool vis[1000002];
long long int p, k, mod = 1000000007, i, ans = 1;
vector<vector<long long int> > v(1000002);
void dfs(long long int i) {
  vis[i] = 1;
  for (long long int j = 0; j < v[i].size(); j++) {
    if (!vis[v[i][j]] && v[i][j] != 0) dfs(v[i][j]);
  }
}
long long int powerful(long long int a, long long int b) {
  if (b == 1)
    return a;
  else if (b == 0)
    return 1;
  else {
    long long int can = (powerful(a, b / 2)) % mod;
    if (b % 2 == 0)
      return (can * can) % mod;
    else
      return ((can * can) % mod * a) % mod;
  }
}
int main() {
  cin >> p >> k;
  for (i = 1; i < p; i++) {
    v[i].push_back((k * i) % p);
    v[(k * i) % p].push_back(i);
  }
  long long int cnt = 0;
  for (i = 1; i < p; i++)
    if (!vis[i]) {
      dfs(i);
      cnt++;
    }
  if (k == 1) cnt++;
  cout << powerful(p, cnt) << endl;
}
