#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const int SIZE = 1e6 + 10;
void MUL(long long &x, long long v) { x = x * v % MOD; }
int main() {
  long long an = 1;
  int p, k;
  scanf("%d%d", &p, &k);
  if (!k) {
    for (int i = (1); i < (p); ++i) {
      MUL(an, p);
    }
    cout << an << endl;
  } else {
    int cnt = 1;
    long long now = k;
    while (now != 1) {
      now = now * k % p;
      cnt++;
    }
    for (int i = 0; i < ((p - 1) / cnt); ++i) {
      MUL(an, p);
    }
    if (k == 1) MUL(an, p);
    cout << an << endl;
  }
  return 0;
}
