#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, k;
  scanf("%d%d", &n, &k);
  if (k == 0) {
    int ans = 1;
    for (int i = 1; i <= n - 1; i++) ans = ans * (long long)n % 1000000007;
    printf("%d\n", ans);
    return 0;
  } else if (k == 1) {
    int ans = 1;
    for (int i = 1; i <= n; i++) ans = ans * (long long)n % 1000000007;
    printf("%d\n", ans);
    return 0;
  }
  long long rk = 1;
  for (int i = 1; i <= n - 2; i++) rk = rk * k % n;
  long long tmp = 1;
  int circ;
  for (int i = 1; i <= n; i++) {
    tmp = tmp * rk % n;
    if (tmp == 1) {
      circ = i;
      break;
    }
  }
  int ans = 1;
  for (int i = 1; i <= (n - 1) / circ; i++)
    ans = ans * (long long)n % 1000000007;
  printf("%d\n", ans);
  return 0;
}
