#include <bits/stdc++.h>
using namespace std;
inline long long ModPow(long long a, long long b, long long mod) {
  if (b == 0) return 1;
  if (b == 1) return a;
  if (b % 2) return (ModPow(a, b - 1, mod) * a) % mod;
  long long z = ModPow(a, b / 2, mod);
  return (z * z) % mod;
}
int main() {
  long long int p, k;
  cin >> p >> k;
  long long MOD = (long long)1e9 + 7;
  if (k == 0) {
    long long int ans = 1;
    for (int i = 1; i < p; i++) ans = (ans * p) % MOD;
    ans = (ans + MOD) % MOD;
    cout << ans << endl;
    return 0;
  }
  if (k == 1) {
    cout << ModPow(p, p, MOD);
    return 0;
  }
  long long int curr = k;
  int q = 0;
  while (1) {
    curr = (curr * k) % p;
    curr = (curr + p) % p;
    q++;
    if (curr == k) break;
  }
  int qq = (p - 1) / q;
  long long int ans = 1;
  for (int i = 1; i <= qq; i++) {
    ans = (ans * p) % MOD;
  }
  ans = (ans + MOD) % MOD;
  cout << ans << endl;
  return 0;
}
