#include <bits/stdc++.h>
using namespace std;
long long p, k;
long long pow(long long a, long long b) {
  long long x = 1, y = a;
  while (b > 0) {
    if (b % 2 == 1) {
      x = (x * y);
      if (x > p) x %= p;
    }
    y = (y * y);
    if (y > p) y %= p;
    b /= 2;
  }
  return x;
}
long long modInverse(long long a, long long m) { return pow(a, m - 2); }
long long univ_inv;
long long cyc_arr[1000001];
long long cyc_ind[1000001];
bool visited[1000001];
long long parent[1000001];
long long rank1[1000001];
void dfs(long long i, long long count) {
  visited[i] = true;
  long long temp = (univ_inv * i) % p;
  if (!visited[temp]) {
    dfs(temp, count + 1);
  } else {
    cyc_arr[count] += 1;
  }
}
void create_set(long long x) {
  parent[x] = x;
  rank1[x] = x;
  cyc_ind[x] = 1;
}
long long find_set(long long x) {
  if (x != parent[x]) parent[x] = find_set(parent[x]);
  return parent[x];
}
void merge_sets(long long x, long long y) {
  long long px = find_set(x);
  long long py = find_set(y);
  if (px == py) return;
  if (rank1[px] > rank1[py]) {
    cyc_ind[px] += cyc_ind[py];
    cyc_ind[py] = 0;
    parent[py] = px;
  } else {
    cyc_ind[py] += cyc_ind[px];
    cyc_ind[px] = 0;
    parent[px] = py;
  }
  if (rank1[px] == rank1[py]) rank1[py] = rank1[py] + 1;
}
int main() {
  cyc_ind[0] = cyc_arr[0] = 0;
  visited[0] = false;
  cin >> p;
  cin >> k;
  univ_inv = modInverse(k, p);
  for (long long i = 0; i < p; i++) {
    create_set(i);
    if (!visited[i]) dfs(i, 1);
  }
  for (long long i = 0; i < p; i++) {
    long long temp1 = (k * i) % p;
    merge_sets(temp1, i);
  }
  long long ans = 1;
  for (long long i = 1; i < p; i++) {
    if (cyc_ind[i] != 0 && (k != 0 && k != 1)) {
      long long temp1 = cyc_ind[i] % 1000000007;
      long long temp2 = (temp1 * cyc_arr[temp1]) % 1000000007;
      temp2 = (temp2 + 1) % 1000000007;
      ans = (ans * temp2) % 1000000007;
    } else if (k == 0 || k == 1) {
      ans = (ans * p) % 1000000007;
    }
  }
  if (k == 1) ans = (ans * p) % 1000000007;
  cout << ans << endl;
}
