#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
long long pow(int a, int b) {
  long long res = 1;
  long long t = a;
  while (b) {
    if (b & 1) res = res * t % MOD;
    t = t * t % MOD;
    b /= 2;
  }
  return res;
}
int main(void) {
  int p, k;
  scanf("%d%d", &p, &k);
  if (k == 1)
    printf("%lld\n", pow(p, p));
  else if (k == 0)
    printf("%lld\n", pow(p, p - 1));
  else {
    long long t = 1;
    int c = 1;
    while (1) {
      t = (t * k) % p;
      if (t == 1) break;
      c++;
    }
    printf("%lld\n", pow(p, (p - 1) / c));
  }
}
