#include <bits/stdc++.h>
using namespace std;
bool vis[1000009] = {false};
vector<int> adj[1000009];
void dfs(int v) {
  vis[v] = true;
  for (int j = 0; j < adj[v].size(); j++) {
    int k = adj[v][j];
    if (!vis[k]) dfs(k);
  }
}
int main() {
  int p, k;
  cin >> p >> k;
  for (int i = 0; i < p; i++) {
    long long tmp = ((long long)k * (long long)i) % p;
    int j = tmp;
    adj[i].push_back(j);
    tmp = ((long long)k * (long long)j) % p;
    if (tmp != i) adj[j].push_back(i);
  }
  if (k <= 1) {
    int c = (k == 1) ? (p) : (p - 1);
    long long res = 1;
    for (int i = 0; i < c; i++) res = (res * (long long)p) % 1000000007LL;
    cout << res << "\n";
    return 0;
  }
  int c = 0;
  for (int i = 1; i < p; i++) {
    if (!vis[i]) {
      dfs(i);
      c++;
    }
  }
  long long res = 1;
  for (int i = 0; i < c; i++) res = (res * (long long)p) % 1000000007LL;
  cout << res << "\n";
  return 0;
}
