#include <bits/stdc++.h>
using namespace std;
long long p, k;
const long long mod = 1000000007;
int s[1100000];
int u[1100000];
long long ans = 1;
long long power1(long long x, int y, long long m = p) {
  if (!y) return 1;
  if (y % 2) return x * power1(x, y - 1, m) % m;
  long long k = power1(x, y / 2, m);
  return k * k % m;
}
int dfs(int v) {
  u[v] = 1;
  if (u[s[v]]) return 1;
  return 1 + dfs(s[v]);
}
int main() {
  ios::sync_with_stdio(0);
  cin >> p >> k;
  if (k == 0) {
    cout << power1(p, p - 1, mod) << "\n";
    return 0;
  }
  for (long long x = 0; x < p; ++x) {
    long long a = k * x % p;
    s[x] = a;
  }
  for (int i = 0; i < p; ++i) {
    if (u[i]) continue;
    int c = dfs(i);
    long long w = power1(k, c);
    if (w == 1) ans *= p % mod;
    ans %= mod;
  }
  cout << ans << "\n";
}
