#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 100;
vector<int> g[N];
int vis[N];
int sz;
void dfs(int u) {
  vis[u] = 1;
  sz++;
  for (int v : g[u]) {
    if (vis[v] == 0) dfs(v);
  }
}
long long mod = 1e9 + 7;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  long long p, k;
  cin >> p >> k;
  if (k == 0) {
    long long ans = 1;
    for (int i = 1; i < p; i++) {
      ans *= p;
      ans %= mod;
    }
    cout << ans;
    return 0;
  }
  long long cur = 0;
  for (int x = 0; x < p; x++) {
    g[x].push_back(cur);
    g[cur].push_back(x);
    cur = (cur + k) % p;
  }
  long long ans = 1;
  for (int i = 0; i < p; i++) {
    if (vis[i] == 0) {
      sz = 0;
      dfs(i);
      long long mul = 1;
      while (sz--) {
        mul = 1ll * mul * k % p;
      }
      if (mul == 1) {
        ans *= p;
        ans %= mod;
      }
    }
  }
  cout << ans;
  return 0;
}
