#include <bits/stdc++.h>
using namespace std;
const long double PI = 3.14159265358979323;
const long long int linf = 1000111000111000111LL;
const long long int inf = 1011111111;
const long long int N = 1000005;
vector<long long int> g[N];
bool vis[N];
void dfs(long long int node) {
  vis[node] = true;
  for (long long int i = 0; i < (long long int)(g[node]).size(); i++) {
    long long int v = g[node][i];
    if (vis[v] == false) {
      dfs(v);
    }
  }
}
long long int power(long long int x, long long int y, long long int p) {
  long long int res = 1;
  x = x % p;
  while (y > 0) {
    if (y & 1) res = (res * x) % p;
    y = y >> 1;
    x = (x * x) % p;
  }
  return res;
}
int32_t main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long int test = 1;
  while (test--) {
    long long int p, k;
    cin >> p >> k;
    if (k == 0) {
      cout << power(p, p - 1, 1000000007);
      continue;
    }
    for (long long int i = 0; i < p; i++) {
      long long int u = (i * k) % p;
      long long int v = i;
      g[u].push_back(v);
      g[v].push_back(u);
    }
    long long int ans = 0;
    for (long long int i = 0; i < p; i++) {
      if (vis[i]) continue;
      ans++;
      dfs(i);
    }
    if (k == 1)
      cout << power(p, ans, 1000000007);
    else
      cout << power(p, ans - 1, 1000000007);
  }
  cerr << '\n'
       << "Time elapsed :" << clock() * 1000.0 / CLOCKS_PER_SEC << " ms\n";
}
