#include <bits/stdc++.h>
using namespace std;
long long power(long long x, long long y, long long p) {
  long long res = 1;
  x = x % p;
  while (y > 0) {
    if (y & 1) res = (res * x) % p;
    y = y >> 1;
    x = (x * x) % p;
  }
  return res;
}
int main() {
  long long p, k;
  scanf("%I64d %I64d", &p, &k);
  if (k == 0) {
    printf("%I64d", power(p, p - 1, 1000000007));
  } else if (k == 1) {
    printf("%I64d", power(p, p, 1000000007));
  } else {
    long long o = 1;
    long long temp = k;
    while (temp != 1) {
      temp = temp * k % p;
      o++;
    }
    printf("%I64d", power(p, ((p - 1) / o), 1000000007));
  }
  return 0;
}
