#include <bits/stdc++.h>
using namespace std;
bool ps[1111111];
const int mod = 1e9 + 7;
int main() {
  int p, k, c = 0;
  long long ans = 1;
  scanf("%d%d", &p, &k);
  for (int i = 0; i < p; ++i) {
    if (ps[i]) continue;
    c++;
    long long b = i;
    while (!ps[b]) ps[b] = 1, b = (b * k) % p;
  }
  if (k != 1) c--;
  while (c--) ans = (ans * p) % mod;
  printf("%d\n", int(ans));
  return 0;
}
