#include <bits/stdc++.h>
using namespace std;
long long int MOD = 1e9 + 7;
long long int fast_pow(long long int a, long long int b) {
  long long int ans = 1;
  long long int mult = a;
  while (b > 0) {
    if (b % 2) {
      ans *= mult;
      ans %= MOD;
    }
    mult *= mult;
    mult %= MOD;
    b /= 2;
  }
  return ans;
}
int main() {
  long long int p, k;
  cin >> p >> k;
  if (k == 0) {
    cout << fast_pow(p, p - 1) << endl;
    return 0;
  }
  long long int exp = k;
  int cycle = 0;
  while (exp != 1) {
    cycle++;
    exp *= k;
    exp %= p;
  }
  cycle++;
  long long int ans = fast_pow(p, (p - 1) / cycle);
  if (k == 1) {
    ans *= p;
    ans %= MOD;
  }
  cout << ans << endl;
  return 0;
}
