#include <bits/stdc++.h>
using namespace std;
template <class T>
inline T bigmod(T p, T e, T M) {
  long long ret = 1;
  for (; e > 0; e >>= 1) {
    if (e & 1) ret = (ret * p) % M;
    p = (p * p) % M;
  }
  return (T)ret;
}
template <class T>
inline T gcd(T a, T b) {
  if (b == 0) return a;
  return gcd(b, a % b);
}
template <class T>
inline T modinverse(T a, T M) {
  return bigmod(a, M - 2, M);
}
long long cnt[1000001], vis[1000001];
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  long long p, k;
  cin >> p >> k;
  for (long long i = 1; i < p; i++) {
    if (vis[i]) continue;
    long long v = i, cc = 0;
    while (v && vis[v] == 0) {
      vis[v] = 1;
      v = (v * k) % p;
      cc++;
    }
    cnt[cc]++;
  }
  long long res = 1;
  for (int i = (0); i < (cnt[1]); ++i) res = (res * p) % 1000000007ll;
  if (k == 1) res = (res * p) % 1000000007ll;
  for (int i = (2); i < (p); ++i) {
    long long v = ((cnt[i] * (long long)i) + 1ll) % 1000000007ll;
    for (int j = (0); j < (cnt[i]); ++j) res = (res * v) % 1000000007ll;
  }
  cout << res << endl;
}
