#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1000000 + 5;
const int mod = (int)1e9 + 7;
int vis[MAXN];
int main() {
  int p, k;
  scanf("%d%d", &p, &k);
  long long ans = 1;
  if (k == 1) {
    for (int i = 0; i < p; i++) {
      ans = ans * p % mod;
    }
    printf("%lld\n", ans);
    return 0;
  }
  for (int i = 1; i < p; i++) {
    if (!vis[i]) {
      ans = ans * p % mod;
      for (int j = i;; j = (long long)j * k % p) {
        if (vis[j]) break;
        vis[j] = 1;
      }
    }
  }
  printf("%lld\n", ans);
  return 0;
}
