#include <bits/stdc++.h>
using namespace std;
const int N = (int)(1e6) + 10;
const int MOD = (int)(1e9) + 7;
int sz[N];
bool visit[N];
int main() {
  long long p, k, n = 0;
  cin >> p >> k;
  if (k == 0) {
    long long ans = 1;
    for (int(i) = 1; (i) <= (p - 1); ++(i)) ans = ans * p % MOD;
    cout << ans << endl;
    return 0;
  }
  for (int(i) = 0; (i) < (p); ++(i))
    if (!visit[i]) {
      sz[++n] = 0;
      long long num = i;
      while (!visit[num]) {
        ++sz[n];
        visit[num] = true;
        num = num * k % p;
      }
    }
  long long ans = 1;
  for (int(i) = 1; (i) <= (n); ++(i)) {
    long long res = 1;
    long long power = k;
    for (int j = 1; j <= sz[i]; j <<= 1) {
      if (sz[i] & j) res = res * power % p;
      power = power * power % p;
    }
    if (res == 1) ans = ans * p % MOD;
  }
  cout << ans << endl;
  return 0;
}
