#include <bits/stdc++.h>
using namespace std;
const int N = 1000001, md = 1e9 + 7;
using namespace std;
int a[N], B[N], n, k, ans, fx[N];
int main() {
  cin >> n >> k;
  a[0] = 1;
  for (int i = 1; i <= n; i++) a[i] = (a[i - 1] * 1ll * n) % md;
  if (k == 0) {
    cout << a[n - 1];
    return 0;
  }
  if (k == 1) {
    cout << a[n];
    return 0;
  }
  for (int i = 1; i < n; i++) B[(i * 1ll * k) % n] = i;
  ans = 1;
  for (int i = 1; i < n; i++)
    if (!fx[i]) {
      int v = i;
      while (!fx[v]) fx[v] = 1, v = B[v];
      ans = (ans * 1ll * n) % md;
    }
  cout << ans;
}
