#include <bits/stdc++.h>
inline long long read() {
  long long x = 0;
  char ch = getchar(), w = 1;
  while (ch < '0' || ch > '9') {
    if (ch == '-') w = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  return x * w;
}
void write(long long x) {
  if (x < 0) putchar('-'), x = -x;
  if (x > 9) write(x / 10);
  putchar(x % 10 + '0');
}
inline void writeln(long long x) {
  write(x);
  puts("");
}
using namespace std;
const long long mo = 1e9 + 7;
long long ksm(long long x, long long y) {
  long long res = 1;
  for (; y; y >>= 1, x = x * x % mo)
    if (y & 1) res = res * x % mo;
  return res;
}
long long p, k;
int main() {
  p = read(), k = read();
  if (k == 0)
    writeln(ksm(p, p - 1));
  else if (k == 1)
    writeln(ksm(p, p));
  else {
    int m = 1;
    long long res = k;
    for (;; ++m) {
      res %= p;
      if (res == 1) break;
      res *= k;
    }
    writeln(ksm(p, ceil((double)(p - 1) / m)));
  }
  return 0;
}
