#include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
int main() {
  ios::sync_with_stdio(false);
  long long p, k;
  cin >> p >> k;
  if (k == 0) {
    long long res = 1;
    for (long long i = 1; i < p; i++) {
      res = (res * p) % mod;
    }
    cout << res << endl;
  } else if (k == 1) {
    long long res = 1;
    for (long long i = 1; i <= p; i++) {
      res = (res * p) % mod;
    }
    cout << res << endl;
  } else {
    int tmp = k;
    int cnt = 1;
    while (tmp != 1) cnt++, tmp = (tmp * k) % p;
    tmp = (p - 1) / cnt;
    long long res = 1;
    for (int i = 0; i < tmp; i++) {
      res = (res * p) % mod;
    }
    cout << res << endl;
  }
  return 0;
}
