#include <bits/stdc++.h>
using namespace std;
const int INF = 1000000002;
const long long INFLL = 100000000000000000ll;
const long long MOD = 1000000007;
int Par[1000005], Size[1000005];
long long E[1000005], P, K;
int find(int n) {
  if (Par[n] == n) return n;
  return Par[n] = find(Par[n]);
}
void join(int a, int b) {
  if (find(a) == find(b)) return;
  Size[find(b)] += Size[find(a)];
  Par[find(a)] = find(b);
}
int main() {
  cin >> P >> K;
  E[0] = 1;
  for (int i = (0); i <= (P - 1); i++) Par[i] = i, Size[i] = 1;
  for (int i = (1); i <= (P); i++) E[i] = (E[i - 1] * P) % MOD;
  if (K == 0) {
    cout << E[P - 1];
    return 0;
  }
  if (K == 1) {
    cout << E[P];
    return 0;
  }
  for (int x = (0); x <= (P - 1); x++) {
    long long n = (K * x) % P;
    join(x, n);
  }
  int c = 0;
  for (int i = (0); i <= (P - 1); i++)
    if (find(i) == i) c++;
  cout << E[c - 1];
}
