#include <bits/stdc++.h>

using namespace std;

#define PI 3.1415926535897932384626433832795028841971693992

#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define ZERO(a) memset(a, 0, sizeof(a))
#define INIT(a) memset(a, 0xff, sizeof(a))
#define FOR(i, n) for (i=0; i<n; i++)
#define FORD(i, n) for (i=n-1; i>=0; i--)
#define FOR2(i, a, b) for (i=a; i<b; i++)
#define FOR2D(i, a, b) for (i=b-1; i>=a; i--)
#define BIT(i, m) (m&(1LL<<(i)))
#define RBIT(i, m) (m&~(1LL<<(i)))
#define ABIT(i, m) (m|(1LL<<(i)))
#define FORB(i, m) for (i=0; i<32; i++) if (BIT(i, m)>0)
#define ALL(a) a.begin(), a.end()
#define OUT(i, n) (i<0 || i>=n)
#define AT(a, i) (a[(i+a.size())%a.size()])
#define IT(v, i) (v.begin()+(i+v.size())%v.size())
#define IT2(v, i, j) IT(v, i), IT(v, j)
#define INSET(a, S) (S.find(a)!=S.end())

typedef vector<int> vi;
typedef long long ll;
typedef vector<ll> vll;
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef vector<string> vs;
typedef list<int> li;
typedef long double ld;

const int mod =1000000007;

ll pow(ll a, ll p)
{
  ll res = 1;
  while(p>0) {
    if (p%2==1) res *= a, res %= mod;
    a *= a, a %= mod, p/=2;
  }
  return res;
}

int main()
{
    ll p,k;
    cin>>p>>k;
    if (k==0) {
        cout<<pow(p,p-1)<<endl;
        return 0;
    }
    if (k==1) {
        cout<<pow(p,p)<<endl;
        return 0;
    }
    ll order=1,a=k;
    while(a!=1) a*=k,a%=p,order++;
    cout<< pow(p,(p-1)/order) <<endl;
    return 0;
}


#pragma comment(linker, "/STACK:102400000,102400000")
#include<cstdio>
#include<ctype.h>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<vector>
#include<cstdlib>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<cmath>
#include<ctime>
#include<string.h>
#include<string>
#include<sstream>
#include<bitset>
using namespace std;
#define ll __int64
#define ull unsigned __int64
#define eps 1e-8
#define NMAX 100000000
#define MOD 1000000007
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define PI acos(-1)
template<class T>
inline void scan_d(T &ret)
{
    char c;
    int flag = 0;
    ret=0;
    while(((c=getchar())<'0'||c>'9')&&c!='-');
    if(c == '-')
    {
        flag = 1;
        c = getchar();
    }
    while(c>='0'&&c<='9') ret=ret*10+(c-'0'),c=getchar();
    if(flag) ret = -ret;
}
const int maxn = 1000000+10;

bool flag[maxn];
int p;

int quick(int a, int b)
{
    int ret = 1;
    while(b)
    {
        if(b&1) ret = (ll)ret*a%p;
        a = (ll)a*a%p;
        b >>= 1;
    }
    return ret;
}

int main()
{
#ifdef GLQ
    freopen("input.txt","r",stdin);
//    freopen("o.txt","r",stdin);
//    freopen("o1.txt","w",stdout);
#endif
    int k;
    scanf("%d%d",&p,&k);
    if(k == 0)
    {
        ll ans = 1;
        for(int i = 1; i < p; i++) ans = ans*p%MOD;
        printf("%I64d\n",ans);
        return 0;
    }
    else if(k == 1)
    {
        ll ans = 1;
        for(int i = 0; i < p; i++) ans = ans*p%MOD;
        printf("%I64d\n",ans);
        return 0;
    }
    ll ans = 1;
    for(int i = 1; i < p; i++) if(flag[i] == 0)
    {
        int x = i;
        while(flag[x] == 0)
        {
            flag[x] = 1;
            x = (ll)x*k%p;
        }
        ans = ans*p%MOD;
    }
    printf("%I64d\n",ans);
    return 0;
}


#include<bits/stdc++.h>

#define NN 1000111

#define mod 1000000007

using namespace std;

typedef long long INT;

INT vst[NN], arr[NN];

INT power(INT u, int n){

	if(n==0) return 1;

	INT ans=power(u, n/2);

	ans=ans*ans%mod;

	if(n&1) ans=ans*u%mod;

	return ans;

}

int main(){

	int n,k,i,j,p;

	cin>>p>>k;

	if(k==0) {cout<<power(p, p-1)<<endl; return 0;}

	if(k==1) {cout<<power(p, p)<<endl; return 0;}

	int step=0;

	for(i=1; i<p; i++){

		if(vst[i]) continue;

		INT u=i, cnt=0;

		while(!vst[u]){

			vst[u]=1;

			u=u*k%p;

			cnt++;

		}

		arr[cnt]++;

	}

	INT ans=1;

	for(i=1; i<=p-1; i++){

		if(!arr[i]) continue;

		INT tmp=power((i*arr[i]+1), arr[i]);

		ans=ans*tmp%mod;

	}

	cout<<ans<<endl;

	return 0;

}


#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<map>
#include<set>
#include<ctime>
#define eps 1e-6
#define LL long long
#define pii pair<int, int>
//#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;

//const int MAXN = 5000000 + 5;
//const int INF = 0x3f3f3f3f;
const LL mod = 1e9 + 7;
int n;
LL p, k;
set<LL> s;
LL fa[1000100];
int Find(LL x) {
    if(x != fa[x]) return fa[x] = Find(fa[x]);
    return x;
}

int cnt[1001000];
int main() {
    //freopen("input.txt", "r", stdin);
    cin >> p >> k;
    s.insert(0);
    LL ans = 1;
    if(k==0) {
        for(int i = 1; i < p; i++) ans = ans * p % mod;
        cout << ans;
        return 0;
    }
    for(int i = 0; i < p; i++) fa[i] = i;
    for(int i = 0; i < p; i++) {
        LL shit = k * i % p;
        int x1 = Find(i), x2 = Find(shit);
        fa[x1] = x2;
    }
    for(int i = 0; i < p; i++) {
        int z = Find(i);
        cnt[z]++;
    }
    for(int i = 1; i < p; i++)
        if(cnt[i]) ans = ans * p % mod;
    if(k == 1) ans = ans * p % mod;
    cout << ans;
    return 0;
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/detail/standard_policies.hpp>
using namespace __gnu_pbds;
using namespace std;
#define getbit(n, i) (((n) & (1LL << (i))) != 0)
#define setbit0(n, i) ((n) & (~(1LL << (i))))
#define setbit1(n, i) ((n) | (1LL << (i)))
#define togglebit(n, i) ((n) ^ (1LL << (i)))
#define lastone(n) ((n) & (-(n)))
char gap = 32;
template<typename T>
ostream& operator<<(ostream &os, const vector<T> &v) {
    os << '{';
    for (const auto &x : v) os << gap << x;
        return os << '}';
}
template<typename A, typename B>
ostream& operator<<(ostream &os, const pair<A, B> &p) {
        return os << '(' << p.first << gap << p.second << ')';
}

template <class T>
void read(T &x) {
    char c;
    for (c = getchar(); c < '0' || c > '9'; c = getchar())
        ;
    for (x = 0; c <= '9' && c >= '0'; c = getchar()) x = x * 10 + (c & 15);
}
#define ll long long
#define lll __int128_t
#define pb push_back
#define mp make_pair
typedef pair < int,int> ii;
typedef vector<ii> vii;
typedef vector<ll>vl;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef tree<
int,
null_type,
less<int>,
rb_tree_tag,
tree_order_statistics_node_update>
ordered_set;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
ll hashPrime = 1610612741;
#define mod 1000000007
ll parent[2000005];
ll rating[2000005];
ll cnt[2000005];
ll findparent(ll root){
    while(parent[root]!=root){
        root = parent[root];
    }
    return root;
}
void findunion(ll root1,ll root2){
    ll par1 = findparent(root1);
    ll par2 = findparent(root2);
    if(rating[par1]>=rating[par2]){
        parent[par2] = par1;
        rating[par1]++;
    }
    else{
        parent[par1] = par2;
        rating[par2]++;
    }
}
void ini(ll n){
    for (ll i = 0; i <= n;i++){
        parent[i] = i;
    }
}
ll modularExponentiation(ll x, ll n, ll M)
{
    if (n == 0)
        return 1;
    else if (n % 2 == 0) //n is even
        return modularExponentiation((x * x) % M, n / 2, M);
    else //n is odd
        return (x * modularExponentiation((x * x) % M, (n - 1) / 2, M)) % M;

 }
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    ll i, j, k, l, n, m;
    cin >> n >> m;
    ini(n);
    if(m==0){
        cout << modularExponentiation(n, n - 1, mod) << "\n";
    }
    else if(m==1){
        cout << modularExponentiation(n, n, mod) << "\n";
    }
    else{
        for (i = 1; i < n;i++){
            ll bash = (i * m) % n;
            findunion(i, bash);
        }
        set<ll> s;
        for (i = 1; i < n;i++){
            parent[i] = findparent(i);
            s.insert(parent[i]);
        }
        ll sz = (ll)s.size();
        cout << modularExponentiation(n, sz, mod) << "\n";
    }
    return 0;
}


/*
Codeforces Contest #334, Div. 2, Problem D:
*/

/* theprof, Dec 1, 2015 */

#include <iostream>
#include <cmath>

#define N 1000000
#define MOD 1000000007

using namespace std;

int main() {
  int p, k;
  long long i;
  long long num = 1;
  long long q;

  // read input parameters
  cin >> p >> k;

  if (k <= 1) {
    for (q=0; q<p-1+k; q++) {
      num = (num*p) % MOD;
    }
  } else {
    bool used[p];

    for (i=0; i<p; i++) {
      used[i] = false;
    }

    for (i=1; i<p; i++) {
      if (!used[i]) {
        num = (num*p) % MOD;
        used[i] = true;
        q = (i*k) % p;
        while (q != i) {
          used[q] = true;
          q = (q*k) % p;
        }
      }
    }
  }
  cout << num << endl;
}


//#define ONLINE_JUDGE

#if defined(ONLINE_JUDGE)
#define _SECURE_SCL 0
#endif

#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <deque>
#include <set>
#include <map>
#include <functional>
#include <memory>
#include <cmath>
#include <climits>
#include <numeric>
#include <tuple>
#include <memory.h>
#include <stdint.h>

#if !defined(__GNUC__)
#else // !defined(__GNUC__)
#define _CrtDbgBreak() __builtin_trap()
#endif // !defined(__GNUC__)

#if defined(ONLINE_JUDGE)
#define LOCAL_TEST 0
#else
#define LOCAL_TEST 1
#endif

#if LOCAL_TEST
struct AssertsCounter
{
    AssertsCounter(): counter(0) {}
    ~AssertsCounter() { std::cout << std::endl << "DIAG: " << (counter == 0 ? "OK" : "FAIL!!!") << " Asserts count: " << counter << std::endl; }
    void Increment() { counter++; }
    uint32_t counter;
};
AssertsCounter g_assertsCounter;
#define LOCAL_ASSERT(expr) { if (!(expr)) {std::cout << "ASSERT FAILED (" << __LINE__ << "): '" << #expr << "'" << std::endl; g_assertsCounter.Increment(); _CrtDbgBreak(); } }
#define LOCAL_ASSERT_EQ(expr1, expr2) { if ((expr1) != (expr2)) {std::cout << "ASSERT FAILED (" << __LINE__ << "): '" << #expr1 << "' == '" << #expr2 << "' (" << (expr1) << " vs " << (expr2) << "')" << std::endl; g_assertsCounter.Increment(); _CrtDbgBreak(); } }
#else
volatile bool isLocalTestEnabled = 0;
#define LOCAL_ASSERT(expr)
#define LOCAL_ASSERT_EQ(expr1, expr2)
#endif

bool g_isLocalPrintEnabled = (bool)(LOCAL_TEST);
#define LOCAL_PRINT() if (!g_isLocalPrintEnabled) { } else std::cout // << .. << ..

typedef std::string string8_t;
typedef long double ld_t;

typedef std::vector<size_t> vector_size_t;
typedef std::vector<int32_t> vector_int32_t;
typedef std::vector<uint32_t> vector_uint32_t;
typedef std::vector<int64_t> vector_int64_t;
typedef std::vector<uint64_t> vector_uint64_t;
typedef std::vector<string8_t> vector_string8_t;

typedef std::vector<vector_size_t> vector_2d_size_t;
typedef std::vector<vector_int32_t> vector_2d_int32_t;
typedef std::vector<vector_uint32_t> vector_2d_uint32_t;
typedef std::vector<vector_int64_t> vector_2d_int64_t;
typedef std::vector<vector_uint64_t> vector_2d_uint64_t;

typedef std::set<size_t> set_size_t;
typedef std::set<int32_t> set_int32_t;
typedef std::set<uint32_t> set_uint32_t;
typedef std::set<int64_t> set_int64_t;
typedef std::set<uint64_t> set_uint64_t;
typedef std::set<string8_t> set_string8_t;

typedef std::multiset<size_t> multiset_size_t;
typedef std::multiset<string8_t> multiset_string8_t;

// Auxiliary functions definition
//
template<typename T> void UpdateMin(T& a, const T b) {a = std::min(a, b);}
template<typename T> void UpdateMax(T& a, const T b) {a = std::max(a, b);}

const ld_t Pi = std::atan(1.0L) * 4.0L;
static const ld_t Eps = 1.0e-09;
template<typename T> bool IsEqual(const T a, const T b) { return std::abs(a - b) < Eps; }
template<typename T> bool IsGreater(const T a, const T b) { return a > b + Eps; }
template<typename T> bool IsLess(const T a, const T b) { return a + Eps < b; }
template<typename T> bool IsGreaterEqual(const T a, const T b) { return !IsLess(a, b); }
template<typename T> bool IsLessEqual(const T a, const T b) { return !IsGreater(a, b); }

template<typename T> string8_t ToStr(const T& val) { std::ostringstream ostr; ostr << val; return ostr.str(); }
template<typename T> bool FromStr(const string8_t& str, T& val) {std::istringstream istr(str); istr >> val; return !!istr; }

template<typename T> std::istream& operator>>(std::istream& ist, std::vector<T>& data)
{
    LOCAL_ASSERT(!!ist);
    for (size_t i = 0; i < data.size(); i++) { ist >> data[i]; }
    return ist;
}

template<typename T> T Read(std::istream& ist)
{
    LOCAL_ASSERT(!!ist);
    T val; ist >> val; return val;
}

template<typename T> std::ostream& operator<<(std::ostream& ost, const std::vector<T>& data)
{
    for (size_t i = 0; i < data.size(); i++) { if (i != 0) { ost << ' '; } ost << data[i]; }
    return ost;
}

#if defined(ONLINE_JUDGE)
template<size_t id> class StopWatch { };
#else
#include <library/lib_stopwatch.h>
#include <library/lib_random.h>
library::random::Rand g_rnd;
#endif

const uint64_t Mod = 1000000007;

template<typename T>
static T FastPow(const T a, const T p)
{
    T res = 1;

    T mask = 1;
    T powPart = a;

    const size_t bitsCount = sizeof(T) * 8;
    for (size_t i = 0; i < bitsCount; i++)
    {
        if (p & mask)
        {
            res *= powPart;
            res %= Mod;
        }
        mask <<= 1;
        powPart *= powPart;
        powPart %= Mod;
    }

    return res;
}

bool Solve(std::istream& ist, std::ostream& ost, const bool multipleTestMode)
{
    StopWatch<1> sw; (void)sw;

    //
    uint64_t p, k;
    ist >> p >> k;

    if (multipleTestMode && !ist)
        return false;

    LOCAL_PRINT() << std::endl << "Next test: " << p << " " << k << std::endl;
    //

    if (k == 0)
    {
        const uint64_t ans = FastPow(p, p - 1);
        ost << ans << std::endl;
        return multipleTestMode;
    }

    if (k == 1)
    {
        const uint64_t ans = FastPow(p, p);
        ost << ans << std::endl;
        return multipleTestMode;
    }

    uint64_t groups = 0;

    vector_size_t used(p + 1);
    uint64_t ans = 1;

    for (uint64_t x = 1; x < p; x++)
    {
        if (used[x])
            continue;

        groups += 1;
        ans *= p;
        ans %= Mod;

        used[x] = 1;

        uint64_t v = x;
        while (!used[v * k % p])
        {
            used[v * k % p] = 1;
            v = v * k % p;
        }
    }

    ost << ans << std::endl;

    return multipleTestMode;
}

#if LOCAL_TEST
void Test()
{
    using namespace library::random;
    const auto genVector = GenFactory::CreateGenVector(GenRange<size_t>(2, 10), GenRange<int32_t>(-100, +200));

    for (size_t t = 0; t < 10; t++)
    {
        const vector_int32_t data = genVector();
        // size_t ans = GetAns(data);
    }
}
#endif

int main(int argc, const char *argv[])
{
#if LOCAL_TEST
    Test();
#endif

    std::ios_base::sync_with_stdio(false);
    std::istream* ist = &std::cin;
    std::ostream* ost = &std::cout;

    std::unique_ptr<std::istream> fileInput;

    if (argc > 1)
    {
        fileInput.reset(new std::ifstream(argv[1]));
        if (!(*fileInput))
        {
            std::cout << "File not found: " << argv[1] << std::endl;
        }
        ist = fileInput.get();
    }

#if defined(ONLINE_JUDGE)
    Solve(*ist, *ost, false);
#else
    while(Solve(*ist, *ost, true)) {};
#endif
}


#include <cstdio>
#include <iostream>
#include <cstring>

using namespace std;

typedef long long ll;

const ll M = 1000000007;

ll p,k;

const int N = 1000005;

int vis[N];

int visit(int x){
	int cnt = 1;
	vis[x] = 1;
	while(!vis[(x * k) % p]) {
		x = (x * k) % p;
		cnt++;
		vis[x] = 1;
	}
	return cnt;
}

ll powx(ll a,ll b){
	ll ans = 1;
	while(b){
		if (b&1)ans = (ans * a) % p;
		b >>= 1;
		a = (a * a) % p;
	}
	return ans;
}

int main(){
	cin >> p >> k;
	ll ans = 1;
	for (int i = 1;i < p;i++)
		if (!vis[i]){
			ll siz = visit(i);
			//cout <<siz<<endl;
			ll t = powx(k,siz);
			//cout << t << endl;
			if (t != 1 && t != 0) ans = (ans * (siz + 1)) % M;
			else ans = (ans * p) % M;
		}
    if (k == 1) ans = (ans * p) % M;
	cout << ans  << endl;
}


#include <bits/stdc++.h>
using namespace std;

/* macros */
// memory
#define zeroset(A) memset((A), 0, sizeof((A)))
#define negset(A) memset((A), -1, sizeof((A)))
#define all(c) (c).begin(), (c).end()
#define pb push_back
// for loops
#define forlop(i,n) for (int i=0; i<n; i++)
#define forlp(i,start,n) for (int i=start; i<n; i++)
#define forone(i,n) for (int i=1; i<n; i++)
#define iter(c,it) for (typeof((c).begin()) it = (c).begin(); it!=(c).end(); it++)
#define iterf(c,bg,it) for (typeof((c).begin()) it = bg; it!=(c).end(); it++)
#define riter(c,it) for (typeof((c).rbegin()) it = (c).rbegin(); it!=(c).rend(); it++)
// input & output
#define intscan(d) scanf("%d", &d)
#define llscan(d) scanf("%lld", &d)
#define dscan(d) scanf("%lf", &d)
#define fast ios::sync_with_stdio(false)
#define inpt(a) freopen(a,"r",stdin)
#define otpt(a) freopen(a,"w",stdout)
#define eol "\n"
// types
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<double, double> pdd;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<vector<ll> > matrix;
#define ff first
#define ss second
#define mp make_pair
// constants
#define EPS 1e-9
#define MAXN 1000005
#define INF INT_MAX
#define NINF INT_MIN

string s;
bool vis[MAXN];
ll k,p;
const ll MOD = 1000000007;

void dfs(int i)
{
    if (!vis[i]){
        vis[i] = true;
        dfs((k*i)%p);
    }
}

int main()
{
    fast;
    int n;
    cin >> p >> k;
    ll ans = 1;
    for (int i=1; i<p; ++i)
        if (!vis[i]){
            dfs(i);
            ans *= p;
            ans %= MOD;
        }
    if (k == 1)
        ans *= p;
    ans %= MOD;
    cout << ans;
    return 0;
}


#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<set>
#include<stack>
#include<map>
#include<vector>
#include<bitset>
#define fi first
#define se second
#define pb push_back
#define mk make_pair
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
ll read()
{
    char ch=getchar();ll x=0,f=1;
    while(ch<'0'||ch>'9')
    {
        if(ch=='-') f=-1;
        ch=getchar();
    }
    x=ch-'0';
    while(1)
    {
        ch=getchar();
        if(ch<'0'||ch>'9') break;
        x=x*10+ch-'0';
    }
    return x*f;
}
const ll mod=1e9+7;
ll p,k,ret;
ll qmul(ll a,ll b,ll Mod)
{
    ll ans=0;
    while(b)
    {
        if(b&1) ans=(ans+a)%Mod;
        b>>=1;a=(a+a)%Mod;
    }
    return ans;
}
ll qpow(ll a,ll b,ll Mod)
{
    ll ans=1;
    while(b)
    {
        if(b&1) ans=qmul(ans,a,Mod);
        b>>=1;a=qmul(a,a,Mod);
    }
    return ans;
}
int main()
{
  //  freopen("B.in","r",stdin);
   // freopen("B.out","w",stdout);
    p=read(),k=read();
    if(k==0) ret=qpow(p,p-1,mod);
    if(k==1) ret=qpow(p,p,mod);
    if(k>1)
    {
        ll l=1,cur=k;
        while(cur!=1)
        {
            cur=(ll) cur*k%p;
            l++;
        }
        ret=qpow(p,(p-1)/l,mod);
    }
    printf("%I64d\n",ret);
  //  fclose(stdin);
  //  fclose(stdout);
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define ll long long
#define F first
#define S second
#define mp make_pair
#define pii pair<int,int>
#define vi vector<int>
#define pq priority_queue
#define pb push_back
#define watch(x) cout << (#x) << " is " << (x) << endl
#define ALL(a) (a.begin()),(a.end())
#define FOR(x,to) for(ll x=0;x<(to);x++)
#define FORR(x,to) for(ll x=1;x<=(to);x++)
#define fastio ios::sync_with_stdio(0); cin.tie(NULL);
const int INF = 0x3f3f3f3f;
const int MOD = 1e9+7;

ll expo(ll x, ll a){
    if(a==0) return 1;
    ll ans = expo(x,a/2);

    ans *= ans;
    ans %= MOD;
    if(a%2) {

        ans *= x;
        ans %= MOD;
    }
    return ans;
}

int main(){
	fastio;
    ll p, k;
    cin >> p >> k;

    if(k == 0){
        cout << expo(p,p-1) << "\n";
    }
    else if(k == 1){
        cout << expo(p,p) << "\n";
    }
    else{
        ll at = k;
        ll fator = 1;
        while(at!=1){

            at = (at*k)%p;
            fator++;
        }

        ll expoente = (p-1)/fator;

        cout << expo(p,expoente) << "\n";

    }

    }


#include <bits/stdc++.h>

using namespace std;

const int mod = 1e9 + 7;
int p, k, ans, vis[1 << 20];
int solve() {
	ans = 1;
	if(!k)
  {
    for(int i=1;i<p;++i)ans=1LL*ans*p%mod;
  }
	else if(k == 1) {
		for(int i = 1; i <= p; ++ i) {
			ans = 1LL * ans * p % mod;
		}
	} else {
		for(int i = 0; i < p; ++i) {
			if(!vis[i]) {
				int len = 0;
				while(!vis[i]) {
					vis[i] = 1;
					++len;
					i = 1LL * i * k % p;
				}
				if(i != 0)
				ans = 1LL * ans * p % mod;
			}
		}
	}
	return ans;
}
int32_t main() {
#ifndef ONLINE_JUDGE
	freopen("data", "r", stdin);
#endif

	cin >> p >> k;
	cout << solve();

}


#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define mod 1000000007
#define M 1000005
#define ll long long
ll p,k;
ll pow(ll a,ll b){
	ll res=1;
	ll x=a;
	while(b){
		if(b&1)res=(res*a)%mod;
		b>>=1;
		a=a*a%mod;
	}
	return res;
}
int main(){
	cin>>p>>k;
	if(k==0){
		cout<<pow(p,p-1)<<endl;
	}
	else if(k==1)cout<<pow(p,p)<<endl;
	else{
		ll sz=1;
		for(ll pos=k%p;pos!=1;++sz)pos=pos*k%p;
		ll cnt=(p-1)/sz;
		cout<<pow(p,cnt)<<endl;
	}
	return 0;
}


//
//  main.cpp
//  D
//
//  Created by 黄宇凡 on 15/12/2.
//  Copyright © 2015年 黄宇凡. All rights reserved.
//

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const long long A=1e9+7;

int main(int argc, const char * argv[]) {
    long long p,k;
    cin>>p>>k;
    if(k>1){
    long long i;
    long long a=1;
    for(i=1;i<=p-1;i++){
        a=a*k;
        a%=p;
        if(a%p==1) break;
    }
    long long j=(p-1)/i;
    long long ans=1;
    for(int l=1;l<=j;l++){
        ans*=p;
        ans%=A;
    }
    ans%=A;
        cout<<ans<<endl;}
    else if(k==1){
        long long ans=1;
        for(int i=1;i<=p;i++){
            ans*=p;
            ans%=A;
        }
        cout<<ans<<endl;
    }
    else if(k==0){
        long long ans=1;
        for(int i=1;i<=p-1;i++){
            ans*=p;
            ans%=A;
        }
        cout<<ans<<endl;
    }
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

const int MAXN = 1<<20;
const int MOD = 1000000007;

bool bio[MAXN];

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(0);

	int p, k, i;
	long long inv;
	long long sol = 1;

	cin>>p>>k;

	if (k == 0)
	{
		for (i = 1; i < p; ++i)
			sol *= p,
			sol %= MOD;
		goto end;
	}

	for (inv = 1; inv * k % p != 1; ++inv);

	if (k == 1)
		sol = p;

	for (i = 1; i < p; ++i)
	{
		if (!bio[i])
		{
			sol *= p;
			sol %= MOD;

			for (long long j = i; !bio[j]; j = j * inv % p)
				bio[j] = true;
		}
	}
	end:
	cout<<sol<<endl;
}


#include<iostream>
#include<fstream>
#include<cstdio>
#include<vector>
#include<string>
#include<cstring>
#include<queue>
#include<map>
#include<set>
#include<algorithm>
#include<iomanip>
#include<bitset>
using namespace std;

const int MOD = 1000000007;

int p, k, ver[1001000], po[1001000];

int main() {
    int i, r = 1;
    //freopen("ttt", "r", stdin);

    cin >> p >> k;

    if(k == 0) {

        for(i = 1; i < p; ++i)
            r = (1LL * r * p) % MOD;

        cout << r;

        return 0;
    }
    if(k == 1) {
        for(i = 0; i < p; ++i)
            r = (1LL * r * p) % MOD;

        cout << r;

        return 0;
    }

    po[0] = 1;
    for(i = 1; i <= 1000000; ++i)
        po[i] = (1LL * po[i - 1] * k) % p;

    for(i = 1; i < p; ++i) if(!ver[i]) {
        int j = i, l = 0;

        do {
            ver[j] = 1;

            ++l;

            j = (1LL * k * j) % p;
        } while(!ver[j]);

        if(po[l] == 1)
            r = (1LL * r * p) % MOD;
        else {
            //r = (1LL * r * 2) % MOD;
        }

    }

    cout << r;

    return 0;
}


#include <bits/stdc++.h>

#define mp make_pair
#define pb push_back
#define ll long long

using namespace std;

const int MOD = 1E9+7;

int parent[1111111];
int nc;

int find( int x ) {
	if ( x == parent[x] ) return x;
	return parent[x] = find(parent[x]);
}

void merge(int a, int b) {
	a = find(a); b = find(b);
	if ( a == b ) return;
	nc --;
	parent[b] = a;
}

ll fmp(ll x, int e) {
	if ( e == 0 ) return 1;
	ll w = fmp(x, e/2);
	w = (w * w) % MOD;
	if ( e&1 ) w = (w * x) % MOD;
	return w;
}

int main() {

	cin.tie(0);
	ios_base::sync_with_stdio(0);

	ll p, k;

	cin >> p >> k;

	if ( k == 0 ) {
		cout << fmp(p, p - 1) << '\n';
		return 0;
	}

	nc = p - (k > 1);

	for ( ll i = 1; i < p; i ++ ) parent[i] = i;

	for ( ll i = 1; i < p; i ++ )
		merge ( i, (i * k) % p );

	cout << fmp ( p, nc ) << '\n';

	return 0;
}


#include <bits/stdc++.h>

using namespace std;

#ifdef Adrian
#include "debug.h"
#else
#define debug(...) 9999
#endif

typedef long long ll;
typedef long double ld;
typedef complex<ld> point;
#define F first
#define S second
#define ii pair<ll,ll>
template <typename G>
struct triple{G F, S, T; };
#define iii triple<int>

struct DS
{
    vector<int> parent;
    vector<int> cont;
    int cc;
    DS(int n) : parent(n), cont(n, 1), cc(0)
    {
        for(int i=0; i<n; i++)
            parent[i] = i;
    }
    int SetOf(int x)
    {
        return parent[x] = (parent[x] == x ? x : SetOf(parent[x]));
    }
    bool Merge(int x, int y)
    {
        x = SetOf(x);
        y = SetOf(y);
        if(x == y) return false;
        if(cont[x] > cont[y])
            swap(x, y);

        cc += (cont[x] == 1 && cont[y] == 1);
        cc -= (cont[x] > 1 && cont[y] > 1);

        parent[x] = y;
        cont[y] += cont[x];
        return true;
    }
};

int main()
{

#ifdef Adrian
    //freopen("test.txt", "r", stdin);
#else
    ios_base::sync_with_stdio(0); cin.tie(0);cout.tie(0);
#endif

    const int mod = 1e9 + 7;
    int p, k;
    cin>>p>>k;

    int ans = 1;
    if(k == 0)
    {
        for(int i=0; i<p - 1; i++)
            ans = (ll)ans * p % mod;
    } else
    {
        int cc = p;
        DS ds(p);
        vector<int> g(p);
        for(int i=0; i<p; i++)
            cc -= ds.Merge(i, (ll)k * i % p);

        if(k > 1)
            cc = ds.cc;
        for(int i=0; i<cc; i++)
            ans = (ll)ans * p % mod;
    }

    cout<<ans<<'\n';

    return 0;
}


#include <cstdio>
#include <algorithm>
#include <vector>
#include <stack>

using namespace std;

int r()
{
    int xy;
    scanf("%d",&xy);
    return xy;
}

bool odw[1000007];
const int mod=1000000007;
long long ile[1000007];
long long cc[1000007];
long long dp[1000007];

int main()
{
    long long wyn=1;
    int p,k;
    scanf("%d%d",&p,&k);
    //odw[0]=1;
        for(int i=0; i<p; i++)
        {
            if(!odw[i])
            {
                int dl=0;
                long long akt=i;
                while(!odw[akt])
                {
                    odw[akt]=1;
                    akt=((long long)k*akt)%p;
                    dl++;
                }
                cc[dl]++;
                //printf("%d %d\n",i,dl);
                //wyn=(wyn*dl)%mod;
            }
        }
    //if(k==0) cos[1]--;
    for(int i=1; i<=p; i++)
    {
        dp[i]=((long long)cc[i]*i)%mod;
        //printf("%d\n",dp[i]);
    }
    for(int i=1; i<=p; i++)
    {
        ile[i]=(ile[i]+dp[i])%mod;
        for(int j=i+i; j<=p; j+=i)
        {
            ile[j]=(dp[i]+ile[j])%mod;
        }
    }
    for(int i=1; i<=p; i++)
    {
        //printf("%d\n",ile[i]);
        if(i==1)
        {
            for(int j=0; j<cc[i]-1; j++)
                wyn=(wyn*(long long)cc[i])%mod;
        }
        else
        {
            for(int j=0; j<cc[i]; j++)
                wyn=(wyn*(long long)ile[i])%mod;
        }

    }
    if(k==1) wyn=(wyn*ile[1])%mod;
    printf("%d",(int)wyn);
	return 0;
}


#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
using namespace std;
const int maxn=1000010,mod=1e9+7;
long long p,k,ans=1,vis[maxn],f[maxn];
void dfs(int n,int l)
{
    if(vis[n]==1)
    {
        f[l]++;
        return;
    }
    vis[n]=1;
    dfs(((long long)n*k)%p,l+1);
}
int main()
{
#ifdef sherco
    freopen("wtf.txt","r",stdin);
    freopen("a.txt","w",stdout);
#endif
    scanf("%I64d%I64d",&p,&k);
    if(k!=0&&k!=1)
    {
        for(int i=1;i<p;i++)
            if(vis[i]==0)
                dfs(i,0);
        for(int i=1;i<=p;i++)
            for(int j=1;j<=f[i];j++)
                ans=((ans*(f[i]*i+1)))%mod;
    }
    else if(k==0)
        for(int i=1;i<p;i++)
            ans=(ans*p)%mod;
    else if(k==1)
        for(int i=1;i<=p;i++)
            ans=(ans*p)%mod;
    printf("%I64d\n",ans);
    return 0;
}


#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>

using namespace std;

typedef long long ll;

int mod = 1e9 + 7;

int add(int i, int j) { return ((i += j) < mod ? i : i -= mod); }
int mult(int i, int j) { return (ll) i * j % mod; }
int pwr(int i, int k) {
    int r = 1;
    while(k) {
        if(k & 1)
            r = mult(r, i);
        i = mult(i, i);
        k >>= 1;
    }

    return r;
}

int P[1000001];
int beb(int a, int m) {
    memset(P, -1, sizeof P);
    int s = sqrt(m);
    mod = m;
    int r = 1;
    int d = pwr(a, m - 2);
    for(int i = 0; i <= s; ++i) {
        if(P[r] == -1) P[r] = i;
        r = mult(r, d);
        if(r == 1) { mod = 1e9 + 7; return i + 1; }
    }

    d = pwr(a, s);
    r = d;
    for(int i = 1; i <= s; ++i) {
        if(P[r] > -1) {
            mod = 1e9 + 7;
            return s * i + P[r];
        }

        r = mult(r, d);
    }

    return -1;
}

int main() {
    int p, k; cin >> p >> k;
    if(k == 1) cout << pwr(p, p);
    else if(k == 0) cout << pwr(p, p - 1);
    else cout << pwr(p, (p - 1) / beb(k, p));

    return 0;
}


/*************************************************************************
	> File Name: 334d.cpp
	> Author:
	> Mail:
	> Created Time: 2015年12月02日 星期三 14时01分02秒
 ************************************************************************/

#include<iostream>
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MOD=1000000007;
const int maxn=1000007;
LL P,K;
LL vis[maxn];
LL num[maxn];
LL getnum(int pos)
{
    LL tep=(num[pos]*pos)%MOD;
    tep=(tep+1)%MOD;
    LL re=1;
    for(int i=1;i<=num[pos];i++)
        re=(re*tep)%MOD;
    return re;
}
int main()
{
    cin >> P>>K;
    memset(vis,0,sizeof(vis));
    memset(num,0,sizeof(num));
    if(K==0){
        LL tepre=1;
        for(int i=1;i<P;i++)
            tepre=(tepre*P)%MOD;
        cout<<tepre<<endl;
        return 0;
    }
    if(K==1){
        long long tepre=1;
        for(int i=1;i<=P;i++)
            tepre=(tepre*P)%MOD;
        cout<<tepre<<endl;
        return 0;
    }
   // cout<<"!!!!"<<endl;
    for(int i=0;i<P;i++){
        if(!vis[i]){
            LL tepnum=0;
            LL pos=i;
            while(!vis[pos]){
                vis[pos]=1;
                tepnum++;
                pos=(K*pos)%P;
            }
            num[tepnum]++;
        }
    }
    //cout<<"!!!!"<<endl;
    LL re=1;
    for(int i=2;i<P;i++){
        if(num[i]){
            re=(re*getnum(i))%MOD;
        }
    }
    //cout<<getnum(3)<<endl;
    cout<<re<<endl;
    return 0;
}


#include <iostream>
#include <cstdio>
#include <cassert>
#include <vector>
#include <algorithm>
#include <cmath>

using namespace std;

typedef long long ll;

const ll MOD = 1000000007;

struct DSU
{
	vector<ll> parent;

	DSU(ll n)
	{
		parent = vector<ll>(n);
		for (ll i = 0LL; i < n; i++) {
			parent[i] = i;
		}
	}

	ll find_set(ll a)
	{
		if (a == parent[a]) {
			return a;
		}
		ll base = find_set(parent[a]);
		parent[a] = base;
		return base;
	}

	void union_set(ll a, ll b)
	{
		a = find_set(a);
		b = find_set(b);
		if (a != b) {
			if (rand() % 2) {
				swap(a, b);
			}
			parent[b] = a;
		}
	}
};

ll count_cycles(ll p, ll k)
{
	DSU dsu(p);
	for (ll i = 1LL; i < p; i++) {
		ll ki = (k * i) % p;
		dsu.union_set(i, ki);
	}

	vector<bool> found(p, false);
	ll count = 0LL;
	for (ll i = 1LL; i < p; i++) {
		ll base = dsu.find_set(i);
		if (!found[base]) {
			found[base] = true;
			count++;
		}
	}
	return count;
}

ll count_solutions(ll p, ll k)
{
	ll cycles;
	if (k == 0) {
		cycles = p - 1;
	}
	else if (k == 1) {
		cycles = p;
	}
	else {
		cycles = count_cycles(p, k);
	}

	ll count = 1LL;
	for (ll i = 0LL; i < cycles; i++) {
		count *= (ll)p;
		count %= MOD;
	}
	return (ll)count;
}

int main()
{
	ll p, k;
	cin >> p >> k;
	ll count = count_solutions(p, k);
	printf("%lld\n", count);

	int end;
	cin >> end;
	return 0;
}


#include <algorithm>
#include <iostream>
#include <sstream>
#include <utility>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <fstream>
#include <cstdio>
#include <string>
#include <vector>
#include <queue>
#include <cmath>
#include <ctime>
#include <stack>
#include <map>
#include <set>

using namespace std;

#define pb push_back
#define ppb pop_back
#define mp make_pair
#define fs first
#define sc second
#define abs(a) ((a) < 0 ? -(a) : (a))
#define sqr(a) ((a) * (a))

typedef unsigned int uint;
typedef long long ll;
typedef unsigned long long ull;

const double eps = 1e-9;
const int mod = (int)1e+9 + 7;
const double pi = acos(-1.);
const int maxn = 1000100;

int snm[maxn];
int sz[maxn];

int getroot(int u) {
	return(snm[u] == u ? u : (snm[u] = getroot(snm[u])));
}

void merge(int u, int v) {
	u = getroot(u), v = getroot(v);
	if(u != v) {
		sz[u] += sz[v];
		snm[v] = u;
	}
}

int isok(ll a, ll b, ll p) {
	ll res = 1;
	while(b) {
		if(b & 1) {
			res = res * a % p;
		}
		a = a * a % p;
		b >>= 1;
	}
	return(res == 1 ? p : 1);
}

int binpow(ll a, ll b) {
	ll res = 1;
	while(b) {
		if(b & 1) {
			res = res * a % mod;
		}
		a = a * a % mod;
		b >>= 1;
	}
	return(res);
}

int main() {

	#ifdef SOL
	{
//		freopen("input.txt", "r", stdin);
//		freopen("output.txt", "w", stdout);
	}
	#else
	{
		srand(time(0));
		const string file = "";
		if(!file.empty()) {
			freopen((file + ".in").c_str(), "r", stdin);
			freopen((file + ".out").c_str(), "w", stdout);
		}
	}
	#endif

	int p, k;
	scanf("%d%d", &p, &k);

	if(k == 0) {
		cout << binpow(p, p - 1);
		return(0);
	}

	for(int i = 0; i < p; i++) {
		snm[i] = i;
		sz[i] = 1;
	}

	for(int i = 0; i < p; i++) {
		merge((k * 1ll * i) % p, i);
	}
	ll ans = 1;
	for(int i = 0; i < p; i++) {
		if(getroot(i) == i) {
			ans = (ans * 1ll * isok(k, sz[i], p)) % mod;
		}
	}

	printf("%lld", ans);

	#ifdef SOL
	{
		fflush(stdout);
		fprintf(stderr, "%.3lf ms\n", 1000. * clock() / CLOCKS_PER_SEC);
		fflush(stderr);
	}
	#endif
	return(0);
}

// by Andrey Kim


#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <cassert>
#include <queue>
#include <bitset>
using namespace std;
#define forr(i, a, b) for(int i = (a); i < (int) (b); i++)
#define forn(i, n) forr(i, 0, n)
#define pb push_back
#define fst first
#define snd second
#define SZ(x) ((int)x.size())
typedef long long ll;
#define dforn(i, n) for(int i = n - 1; i >= 0; i--)
const int MAXN=-1;
const ll MOD=(ll)1e9+7;

ll p,k;

int main() {
  //~ freopen("input.in","r",stdin);
  while(scanf("%lld%lld",&p,&k)>=1){
    ll l=k==0?p-1:(k==1?p:-1);
    ll ans=1;
    if(l==-1){
      ll t=1,v=k;
      while(v!=1){
        v=(v*k)%p;t++;
      }
      l=p/t;
    }
    forn(i,l){
      ans=(ans*p)%MOD;
    }
    printf("%lld\n",ans);
  }
  return 0;
}


#include <bits/stdc++.h>
using namespace std;

const int N = 1000000 + 5;
const int MOD = (int)1e9 + 7;

int a[N];
bool vis[N];
int p, k;

int main()
{
    cin >> p >> k;
    if (k == 0) {
        int ans = 1;
        for (int i = 1; i < p; ++i) {
            ans = (long long)ans * p % MOD;
        }
        cout << ans << endl;
        exit(0);
    }
    for (int i = 1; i < p; ++i) {
        a[i] = (long long)k * i % p;
    }
    int ans = 1;
    for (int i = 0; i < p; ++i) {
        if (!vis[i]) {
            int size = 0;
            int j = i;
            int tmp = 1;
            while (!vis[j]) {
                vis[j] = true;
                j = a[j];
                size++;
                tmp = (long long)tmp * k % p;
            }
            if (size == 1) {
                int cnt = k == 1 ? p : 1;
                ans = (long long)ans * cnt % MOD;
            } else {
                assert(tmp == 1);
                ans = (long long)ans * p % MOD;
            }
        }
    }
    cout << ans << endl;
}


#include <bits/stdc++.h>
#define f first
#define s second
#define ll long long
#define mp make_pair
#define pb push_back

using namespace std;

double eps = 1e-9;
const int INF = 1e9+7;
const int MAXN = int (2e6+7);

int n, p, k, u[MAXN], ans = 1, mod = INF;

void dfs(int v) {
	u[v] = 1;
	int x = (k * 1ll * v) % p;
	if(!u[x])
		dfs(x);
}

int main () {
   	//freopen("input.in", "r", stdin);
   	//freopen("output.txt", "w", stdout);

    cin >> p >> k;
    int i = 1;
    if(k == 1) {
    	i = 0;
    }
    for(; i < p; i ++) {
    	if(!u[i]) {
    		dfs(i);
    		ans = (ans * 1ll * p) % mod;
    	}
    }
    cout << ans;
    return 0;
}


#include <cmath>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long ll;
const int mod7=1000000007;

int main()
{
    #ifndef ONLINE_JUDGE
        freopen("input.txt","r",stdin);
        freopen("output.txt","w",stdout);
    #endif
    int mod,k;scanf("%d%d",&mod,&k);
    int t=1,j;
    for (int i=1;i<mod;i++)
    {
        t=ll(t)*k%mod;
        if (t==1) {j=i;break;}
    }
    if (k==0) j=1;
    int ans=1;
    for (int i=1;i<=(mod-1)/j;i++) ans=ll(ans)*mod%mod7;
    if (k==1) ans=ll(ans)*mod%mod7;
    printf("%d\n",ans);
    return 0;
}


#include <bits/stdc++.h>
#include <ctime>

#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx")

using namespace std;

#define space ' '
#define enter "\n"
#define fi first
#define se second
#define mp make_pair
#define ALL(x) x.begin(), x.end()
#define bits(x) __builtin_popcount(x)
#define bitsll(x) __builtin_popcountll(x)
#define crr(a) cerr << #a << " = " << a << "\n"
#define precision(a) fixed << setprecision(a)

typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
typedef pair <int, int> pii;
typedef set <int> si;
typedef map <int, int> mii;
typedef pair <ll, ll> pll;
typedef vector <int> vi;
typedef vector <pii> vii;

inline bool isDigit (char c) {
	return '0' <= c && c <= '9';
}

template <class T>
inline T sqr (T x) {
	return x * x;
}

template <class T>
inline bool isSquare (T x) {
	T y = sqrt(x + 0.5);
	return (y * y) == x;
}

template <class T1, class T2>
inline T1 gcd (T1 a, T2 b) {
	return b ? gcd(b, a % b) : a;
}

template <class T1, class T2>
inline T1 eqMin (T1 & x, const T2 & y) {
	if (T1(y) < x)
		return x = y;
	return x;
}

template <class T1, class T2>
inline T1 eqMax (T1 & x, const T2 & y) {
	if (T1(y) > x)
		return x = y;
	return x;
}

template <class T1, class T2>
inline T1 min (const T1 & x, const T2 & y) {
	return x < (T1) y ? x : (T1) y;
}

template <class T1, class T2>
inline T1 max (T1 & x, const T2 & y) {
	return x > (T1) y ? x : (T1) y;
}

template <typename T>
inline T getint () {
	T x = 0, p = 1;
	char ch;
	do {
		ch = getchar();
	} while (ch <= ' ');
	if (ch == '-')
		p = -1, ch = getchar();
	while (ch >= '0' && ch <= '9')
		x = x * 10 + ch - '0', ch = getchar();
	return x * p;
}

template <class T1, class T2>
ostream & operator << (ostream & os, const pair <T1, T2> & p) {
	return os << '(' << p.fi << ", " << p.se << ')';
}

template<typename T>
auto operator<<(ostream &os, const T &v) -> decltype(v.begin(), v.end(), declval<ostream &>()) {
	os << '{';
	bool was = false;
	for (const auto &x : v) {
		if (was)
			os << ", ";
		was = true;
		os << x;
	}
	os << '}';
	return os;
}

template <size_t sz>
ostream & operator << (ostream & os, const bitset <sz> & bit) {
	os << '/';
	for (int i = 0; i < sz; i++)
		os << bit[i];
	os << '\\';
	return os;
}

const double PI = acos(-1);
const double EPS = 1e-8;
const int INF = (int) 2e9;
const ll LINF = (ll) 2e18;
const int MOD = (int) 1e9 + 7;
const int MAXN = (int) 3e6 + 10;

int p, k, t;
bool used[MAXN];

void dfs (int x) {
	used[x] = true;
	int to = ((ll) x * k) % p;
	if (!used[to]) {
		dfs(to);
	}
}

int main () {
	ios_base::sync_with_stdio(false);
	cin >> p >> k;
	for (int i = 0; i < p; i++) {
		if (!used[i]) {
			t++;
			dfs(i);
		}
	}
	ll ans = 1;
	for (int i = 1; i < t + (k == 1); i++) {
		ans *= p;
		ans %= MOD;
	}
	cout << ans;
}


#include<bits/stdc++.h>
/*断你妹。。*/
using namespace std;
typedef pair<int,int> pr;
typedef long long ll;
#define maxn 1000005
#define mod 1000000007

bool vis[maxn];

ll fastPow(ll a,int b){
    ll res=1;
    while(b){
        if (b&1) res=res*a%mod;
        b>>=1;
        a=a*a%mod;
    }
    return res;
}

int main(){
    ll p,k;
    scanf("%I64d%I64d",&p,&k);
    if (k==0){
        printf("%I64d\n",fastPow(p,p-1));
        return 0;
    }
    if (k==1){
        printf("%I64d\n",fastPow(p,p));
        return 0;
    }
    int cnt=0;
    for (int i=1;i<p;i++){
        if (vis[i]) continue;
        ll j=i;
        while(!vis[j]){
            vis[j]=true;
            j=j*k%p;
        }
        cnt++;
    }
    printf("%I64d\n",fastPow(p,cnt));
    return 0;
}


#include <stdio.h>
#include <memory.h>
#include <iostream>
using namespace std;
int c[203], n, k[203][203], idx[203];
bool co[203];
inline bool done() {
    int i;
    for ( i = 1; i <= n; ++i ) {
        if ( !co[i] ) return 0;
    }
    return 1;
}
void complete( int x, int id[] ) {
    int i, kn = k[x][0];
    for ( i = 1; i <= kn; ++i ) {
        --id[k[x][i]];
    }
}
int deal( int s ) {
    memset( co, 0, sizeof( co ) );
    int idy[203];
    memcpy( idy, idx, sizeof( idx ) );
    int cnt = 0, i;
    do {
        bool flag = 1;
        while ( flag ) {
            flag = 0;
            for ( i = 1; i <= n; ++i ) {
                if ( c[i] == s ) {
                    if ( !co[i] && !idy[i] ) {
                        co[i] = 1;
                        complete( i, idy );
                        flag = 1;
                        ++cnt;
                    }
                }
            }
        }
        ++cnt;
        ++s;
        if ( s > 3 ) s = 1;
    } while ( !done() );
    return cnt - 1;
}
int main( int argc, char *argv[] )
{
    int i;
    scanf( "%d", &n );
    for ( i = 1; i <= n; ++i ) scanf( "%d", c + i );
    int ki, j;
    memset( idx, 0, sizeof( idx ) );
    memset( k, 0, sizeof( k ) );
    for ( i = 1; i <= n; ++i ) {
        scanf( "%d", &ki );
        int t;
        for ( j = 1; j <= ki; ++j ) {
            scanf( "%d", &t );
            k[t][++k[t][0]] = i;
            ++idx[i];
        }
    }
    int tm, ma = 0x3f3f3f3f;
    //puts( "##########" );
    tm = deal( 1 );
    //printf( "%d    ++++++\n", tm );
    if ( ma > tm ) ma = tm;
    tm = deal( 2 );
    //printf( "%d    ########\n", tm );
    if ( ma > tm ) ma = tm;
    tm = deal( 3 );
    if ( ma > tm ) ma = tm;
    //printf( "%d    @@@@@@@@@\n", tm );
    cout<<ma<<endl;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

int main()
{
    string s;
    cin>>s;
    int n = s.size();
    int cnt4= 0, cnt7=0;
    int lucky = 1;
    for(int i = 0; i < n; ++i)
    {
        if(s[i] == '4')
            cnt4++;
        else if(s[i] == '7')
            cnt7++;
        else
        {
            lucky = 0;
            break;
        }
    }

    if(lucky && cnt4 == cnt7)
    {
        cout<<s<<endl;
        return 0;
    }

    if(!(n%2))
    {
        string tmp;
        for(int i = 0; i < n; i++)
        {
            if(i < n/2)
                tmp+= '4';
            else
                tmp+= '7';
        }
        string tmp2 = tmp;
        do
        {
            int flag = 1;
                for(int i = 0; i < tmp.size(); i++)
                {
                    if(tmp[i] < s[i])
                    {
                        flag = 0;
                        break;
                    }
                    else if(tmp[i] > s[i])
                    {
                        break;
                    }
                }

                if(flag)
                {
                    cout<<tmp<<endl;
                    return 0;
                }
                next_permutation(tmp.begin(), tmp.end());
        }
        while(tmp != tmp2);
    }
        if(n%2)
        {
            n++;
            for(int i = 0; i < n; i++)
            {
                if(i < n/2)
                    cout<<"4";
                else
                    cout<<"7";
            }
            return 0;
        }
        else
        {
            n+=2;
            for(int i = 0; i < n; i++)
            {
                if(i < n/2)
                    cout<<"4";
                else
                    cout<<"7";
            }
            return 0;
        }

    return 0;
}


//Optimise
#include <bits/stdc++.h>
using namespace std;

// #define multitest 1
#ifdef WIN32
#define db(...) ZZ(#__VA_ARGS__, __VA_ARGS__);
#define pc(...) PC(#__VA_ARGS__, __VA_ARGS__);
template <typename T, typename U>
ostream &operator<<(ostream &out, const pair<T, U> &p)
{
	out << '[' << p.first << ", " << p.second << ']';
	return out;
}
template <typename Arg>
void PC(const char *name, Arg &&arg)
{
	while (*name == ',' || *name == ' ')
		name++;
	std::cerr << name << " { ";
	for (const auto &v : arg)
		cerr << v << ' ';
	cerr << " }\n";
}
template <typename Arg1, typename... Args>
void PC(const char *names, Arg1 &&arg1, Args &&... args)
{
	while (*names == ',' || *names == ' ')
		names++;
	const char *comma = strchr(names, ',');
	std::cerr.write(names, comma - names) << " { ";
	for (const auto &v : arg1)
		cerr << v << ' ';
	cerr << " }\n";
	PC(comma, args...);
}
template <typename Arg1>
void ZZ(const char *name, Arg1 &&arg1)
{
	std::cerr << name << " = " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void ZZ(const char *names, Arg1 &&arg1, Args &&... args)
{
	const char *comma = strchr(names + 1, ',');
	std::cerr.write(names, comma - names) << " = " << arg1;
	ZZ(comma, args...);
}
#else
#define db(...)
#define pc(...)
#endif

using ll = long long;
#define f first
#define s second
#define pb push_back
auto TimeStart = chrono::steady_clock::now();

const int nax = 2e5 + 10, mod = 1000000007;

void solve(int caseNo)
{
	vector<pair<int, int>> pos;
	int a, b;
	string s;
	cin >> a >> b >> s;
	pos.pb({0, 0});
	for (auto c : s)
	{
		auto b = pos.back();
		switch (c)
		{
		case 'U':
			b.s++;
			pos.pb(b);
			break;
		case 'D':
			b.s--;
			pos.pb(b);
			break;
		case 'L':
			b.f--;
			pos.pb(b);
			break;
		case 'R':
			b.f++;
			pos.pb(b);
			break;
		default:
			break;
		}
	}
	auto back = pos.back();
	int x = back.f, y = back.s;
	db(x, y);
	pos.pop_back();
	for (auto elem : pos)
	{
		int a1 = a - elem.f;
		int b1 = b - elem.s;
		db(a1, b1);
		if (x == 0)
		{
			if (y == 0)
			{
				if (a1 == 0 && b1 == 0)
				{
					cout << "Yes\n";
					return;
				}
			}
			else
			{
				if (a1 == 0 && b1 % y == 0)
				{
					if (b1 / y >= 0)
					{
						cout << "Yes\n";
						return;
					}
				}
			}
		}
		else if (y == 0)
		{
			if (a1 % x == 0 && b1 == 0)
			{
				if (a1 / x >= 0)
				{
					cout << "Yes\n";
					return;
				}
			}
		}
		else
		{
			if (a1 % x == 0 && b1 % y == 0 && ((a1 / x) == (b1 / y)))
			{
				if (a1 / x >= 0)
				{
					cout << "Yes\n";
					return;
				}
			}
		}
	}
	cout << "No\n";
}

int main()
{
#ifndef WIN32
	ios_base::sync_with_stdio(0);
	cin.tie(0);
#endif
	int t = 1;
#ifdef multitest
	cin >> t;
#endif
	for (int i = 0; i < t; ++i)
		solve(i);
#ifdef TIME
	cerr << "\n\nTime elapsed: " << chrono::duration<double>(chrono::steady_clock::now() - TimeStart).count() << " seconds.\n";
#endif
	return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define pb push_back
#define r_0 return 0
#define fr first
#define se second
#define TIME ios_base::sync_with_stdio(0);
using namespace std;
const ll N=1e5 ;
ll  n  , b , c , d , ans , m , cnt , x  , used[N];
vector< string > v , v1 ;
string s ,s1  ;
set<char>st;
map<string , ll > mp ;
char q ;
int main()
{
    cin >> s ;
    cin >> x ;
    for(  ll i =1 ;i <= x; i ++ )
    {
        cin >> s1 ;
        v1.pb(s1) ;
        if( s1[1] == s[0] )
            ans ++ ;
        if( s == s1 )
            cnt ++ ;
    }
    if( cnt >= 1  ){
        cout << "YES" ;r_0 ; }
    if( ans >= 1 )
        for( ll i = 0 ;i < v1.size() ; i ++ )
        if( v1[i][0] == s[1])
        {
            cout << "YES" ; r_0 ;
        }
    cout << "NO"  ;
}


/*
 * 429C. Guess the Tree.cpp
 *
 *  Created on: Jul 20, 2015
 *      Author: Osama Hatem
 */

#include <bits/stdtr1c++.h>
#include <ext/numeric>

using namespace std;

int N, c[25];
map<int, bool> dp;

bool solve(int activeMask) {
    int idx = N;
    for (int i = N - 1; !(activeMask & (1 << i)) && i >= 0; i--)
        idx = i;
    if (idx == N)
        return activeMask == 1 << (N - 1);
    if (dp.count(activeMask))
        return dp[activeMask];
    bool ret = false;
    vector<int> active;
    for (int i = 0; i < N; i++)
        if ((1 << i) & activeMask)
            active.push_back(i);
    int sz = active.size();
    for (int i = 3; !ret && i < (1 << sz); i++) {
        if (!(i & (i - 1)))
            continue;
        int tempSum = 0, newMask = activeMask | (1 << idx);
        for (int j = 0; j < sz; j++)
            if (i & (1 << j))
                tempSum += c[active[j]], newMask ^= 1 << active[j];
        if (tempSum != c[idx] - 1)
            continue;
        ret |= solve(newMask);
    }
    return dp[activeMask] = ret;
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("in.in", "r", stdin);
//  freopen("out.out", "w", stdout);
#endif

    cin >> N;
    for (int i = 0; i < N; i++)
        cin >> c[i];
    sort(c, c + N);
    int mask = 0, cur = 0;
    for (; cur < N && c[cur] == 1; cur++)
        mask |= 1 << cur;
    cout << (solve(mask) ? "YES" : "NO") << endl;
    return 0;
}


#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>

#define maxN    100005

using namespace std;

string s;
int dd[1000], n, b[20];
char ch[maxN], a[maxN];

void process() {
    cin >> s; n = s.length();
    for(int i = 0; i < n; i++) ch[i + 1] = s[i];

    // dem
    int sl = 0, demquest = 0;
    for(int i = 1; i <= n; i++)
    if ('A' <= ch[i] && ch[i] <= 'J' && dd[ch[i] - 'A' + 1] == 0) {
        ++sl; dd[ch[i] - 'A' + 1] = 1;
    }
    else
    if (ch[i] == '?') ++demquest;

    for(int i = 1; i <= sl; i++) b[i] = 10 - i + 1;

    int mul = 1;
    if (ch[1] == '?') mul = 9, demquest--; else
    if ('A' <= ch[1] && ch[1] <= 'J') b[1] = 9;

    // tinh
    long long res = 1;
    for(int i = 1; i <= sl; i++) res *= b[i];
    res *= mul;
    cout << res;
    for(int i = 1; i <= demquest; i++) cout << 0;
    cout << endl;
}

int main() {
    //freopen("inp.txt", "r", stdin); freopen("out.txt", "w", stdout);
    process();
    return 0;
}


#include <iostream>
#include <string>
#include <utility>
#include <string>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;

#define modulo 1000000007
#define pi 3.1415926535897932384

typedef long long int ll;
typedef double d;
typedef string str;
typedef char ch;

void AWAD(){
    std::ios::sync_with_stdio(false);
    cin.tie(0);
}
int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
}
bool cmp (ll a, ll b){

    if(a==0 && b>a)
        return false;
    if(a<b)
        return true;
    return false;
}
bool vis[222222222];
int ndex[40000];
void seive(){
    int i , j;
    for(i=2;i<=5000;i++)
        if(!vis[i])
            for(j=i+i;j<=5000;j+=i)
                vis[j] = 1;
}

int main(){
    str s[12] ={"C","C#","D","D#","E","F","F#","G","G#","A","B","H"};
    str a, b, c;
    cin >> a >> b >> c;
    int a1[12] = {0};
    for(int i = 0; i < 12; i++){

        if(a==s[i] || b == s[i] || c == s[i]){
            a1[i] = 1;
        }
    }
    for(int i = 0; i < 12; i++){
        if(a1[i]){
            if(a1[(i+4)%12] && a1[(i+7)%12]){
                cout << "major\n";
                return 0;
            }
            if(a1[(i+3)%12] && a1[(i+7)%12]){
                cout << "minor\n";
                return 0;
            }
        }
    }

    cout << "strange\n";
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define TR(i,v)         for(__typeof((v).begin())i=(v).begin();i!=(v).end();++i)
#define DEBUG(x)        cout << #x << " = " << x << endl;
#define SIZE(p)         (int)(p).size()
#define MP(a, b)        make_pair((a), (b))
#define ALL(p)          (p).begin(), (p).end()
#define rep(i, n)       for(int (i)=0; (i)<(int)(n); ++(i))
#define REP(i, a, n)    for(int (i)=(a); (i)<(int)(n); ++(i))
#define FOR(i, a, b)    for(int (i)=(int)(a); (i)<=(int)(b); ++(i))
#define FORD(i, b, a)   for(int (i)=(int)(b); (i)>=(int)(a); --(i))
#define CLR(x, y)       memset((x), (y), sizeof((x)))
typedef long long LL;
typedef pair<int, int> pii;
const int mod=(int)1e9+7;
int f[200005],f_inv[200005];
inline int add(int x,int y) {
    x+=y;
    if(x>=mod)  x-=mod;
    return x;
}
inline int sub(int x,int y) {
    x-=y,x%=mod;
    if(x<0)     x+=mod;
    return x;
}
inline int mul(LL x,LL y) {
    x*=y,x%=mod;
    return x;
}
int pw(int a,int p) {
    int r=1;
    for(;p;p>>=1,a=mul(a,a)) if(p&1)
        r=mul(r,a);
    return r;
}
void pre() {
    f[0]=1;
    FOR(i,1,200000)
        f[i]=(LL)i*f[i-1]%mod;
    f_inv[200000]=pw(f[200000],mod-2);
    FORD(i,200000-1,0)
        f_inv[i]=(LL)(i+1)*f_inv[i+1]%mod;
}
int C(int n,int m) {
    int c=f[n];
    c=mul(c,f_inv[m]);
    c=mul(c,f_inv[n-m]);
    return c;
}
int g(int n,int a) {
    if(n==0)    return 0;
    if(n==1) {
        return a==0;
    }
    if(a) return sub(C(n-1,a-1),g(n-1,a-1));
    return 0;
}
int main(int argc, char const *argv[]) {
#ifndef ONLINE_JUDGE
    freopen("D.in", "r", stdin);
    // freopen("out", "w", stdout);
#endif
    pre();
    int n,m,t;  cin>>n>>m>>t;
    int a=n;    n=n+m;
    int res=g(n,a);
    // DEBUG(res);
    // DEBUG(g(1,0));
    // DEBUG(res);
    if(t==0)    res=sub(C(n,a),res);
    printf("%d\n",res);
    return 0;
}


#include <cstdio>
#include <algorithm>
#include <iostream>
using namespace std;

string temp = "ACTG";

int func(string s) {
	int answer = int(1e6);
	for(int i = 0; i < (int)s.size() - 3; i++) {
		string new_s = "";
		new_s += s[ i ];
		new_s += s[ i  + 1];
		new_s += s[ i + 2 ];
		new_s += s[ i + 3 ];

		int nedo = 0;
		for(int j = 0; j < temp.size(); j++) {
			if(temp [ j ] == new_s[ j ]) continue;

			nedo += min(26 - abs(temp[ j ] - new_s[ j ]), abs(temp[ j ] - new_s[ j ]));
		}
		answer = min(answer, nedo);
	}

	return answer;
}

int main() {
	int n;
	scanf("%i", &n);

	string s;
	cin >> s;

	printf("%i ", func(s));
}


#include <cstdio>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <algorithm>
#include <cmath>

#define INF 100000007
#define MP(a, b) make_pair(a, b)
typedef long long ll;
const int maxn = 100010;
using namespace std;
typedef pair<int, int> P;
int n, d, a[maxn], b[maxn], c[maxn], s[50], bb[maxn], num;
ll x;
ll getNextX()
{
    x = (x * 37 + 10007) % 1000000007;
    return x;
}
void init()
{
    ll i;
    for(i = 0; i < n;i++)
    {
        a[i] = i + 1;
    }
    for(i = 0; i < n; i++)
    {
        swap(a[i], a[getNextX() % (i + 1)]);
    }
    for(i = 0; i < n; i++)
    {
        if (i < d)
            b[i] = 1;
        else
            b[i] = 0;
    }
    for(i = 0; i < n; i++)
    {
        swap(b[i], b[getNextX() % (i + 1)]);
    }
}
#define NN 30
int main()
{
//  freopen("in.txt", "r", stdin);
//  freopen("out.txt", "w", stdout);
    int i, j, k;
    scanf("%d%d%I64d", &n, &d, &x);
    init();
    for(i = 0; i < n; i++)
    if(b[i])
        bb[num++] = i;
    if(n < NN + 20)
    {
        for(i = 0; i < n; i++)
        {
            for(j = 0, k = 0; j < num && bb[j] <= i; j++)
                k = max(k, a[i - bb[j]]);
            printf("%d\n", k);
        }
    }
    else
    {
        for(i = 0; i < n; i++)
        if(n - a[i] <= NN)
            s[n - a[i]] = i;
        for(i = 0; i < n; i++)
        {
            for(j = 0; j <= NN; j++)
            if( s[j] <= i && b[i - s[j]] )
            {
                printf("%d\n", n - j);
                break;
            }
            if(j <= NN)
                continue;
            for(j = 0, k = 0; j < num&& bb[j] <= i; j++)
                k = max(k, a[i - bb[j]]);
            printf("%d\n", k);
        }
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
#define ll long long
#define dd double
#define MOD1 1000000007
#define MOD2 998244353
#define nl cout<<endl
#define rt ll Q[100005]={0}
#define mp make_pair
#define test() ll t;cin>>t;while(t--)
#define pb push_back
#define ff first
#define ss second
#define all(v) v.begin(),v.end()
#define s(ar,n) sort(ar,ar+n)
#define rs(ar,n) sort(ar, ar+n, greater<ll>())
#define oa(a,n) for(ll i=0;i<n;i++)cout<<a[i]<<" ";nl
#define cn(a,n) for(ll i=0;i<n;i++)cin>>a[i];
#define ov(a,n) for(ll i=n-1;i>=0;i--)cout<<a[i]<<" ";nl
#define ovp(a,n) for(ll i=0;i<n;i++)cout<<a[i].ff<<" "<<a[i].ss<<endl;
#define maxa(ar,N) *max_element(ar,ar+N)
#define mina(ar,N) *min_element(ar,ar+N)
#define fastio() ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
typedef pair<ll,ll> pii;
ll powe(ll n,ll m){if(m==0)return 1;ll t=powe(n,m/2);if(m%2==0)return (t*t);return (((t*t))*n);}
ll mpowe(ll n,ll m,ll MOD){if(m==0)return 1;ll t=mpowe(n,m/2,MOD);t%=MOD;if(m%2==0)return (t*t)%MOD;return (((t*t)%MOD)*n)%MOD;}
ll logtwo(ll n){if(n==1)return 0;if(n==0) return -1;return logtwo(n/2)+1;}
int solve(string s[],int curri,int currj,int n,int m)
{
	//cout<<curri<<" "<<currj<<endl;
	int mini = 50,x,y;
	for (int i = curri; i < n; ++i)
	{
		for (int j = currj; j < m; ++j)
		{
			if(i==curri && j==currj)
				continue;
			if(s[i][j]=='*')
			{
				if(i+j<mini)
				{
					mini = i+j;
					x=i;
					y=j;
				}
				else if(i+j==mini)
				{
					if(y<j)
					{
						x=i,y=j;
					}
				}
			}
		}
	}
	if(mini==50)
		return 0;
	return 1+ solve(s,x,y,n,m);
}
int main()
{
    fastio();
    #ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
    #endif
    int n,m;
    cin>>n>>m;
    string s[n];
    cn(s,n);
    int ans=s[0][0]=='*'?1:0,i=0,j=0,c=0;
    ans+=solve(s,i,j,n,m);
    cout<<ans<<endl;
}


#include <iostream>
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <string>
#include <cstring>
#include <cmath>
#include <map>
#include <queue>
#include <set>
using namespace std;
const int maxn = 200010;
int col[maxn],k[maxn],cnt[maxn];//cnt 当前位置的颜色数量
set <int> q;
int main()
{
	int n,m;
	cin>>n>>m;
	for(int i=1;i<=n;i++){
		scanf("%d",&col[i]);
	}
	int sum=0;
	for(int i=1;i<=m;i++){
		scanf("%d",&k[i]);
		if(k[i]>0)
		q.insert(i);
		sum+=k[i];
	}
	int l=1,r;
	int ans=1e9;
	for(r=1;r<=n;r++){
		if(++cnt[col[r]]==k[col[r]]) q.erase(col[r]);
		if(q.empty()){//找到所有颜色且长度>=k[i]
			while(l<=r&&cnt[col[l]]>k[col[l]])	cnt[col[l++]]--;
			ans=min(ans,r-l+1-sum);
		}
	}
//	cout<<ans<<endl;
	if(ans>=1)
		printf("NO\n");
	else
		printf("YES\n");

}


// In the Name of Allah
// Ya Ali!
#include <bits/stdc++.h>
#pragma GCC optimize ("O2")
#pragma GCC optimize ("unroll-loops")

using namespace std;

const int maxn = 402 ;

int n , dp[maxn][maxn] , mod = 1e9 + 7 , c[maxn] , c2[maxn][maxn] ;

int main()
{
//Let's TOF
scanf("%d" , &n) ;

for(int i = 1 ;i <= n+1 ; i ++)c[i] = i*(i-1) ;

for(int i = 1 ;i <= n+1 ; i ++)
 for(int j = 0 ; j <= i ; j ++)
  c2[i][j] = j*(i-j);

dp[1][1] = 1;
dp[1][0] = 1;

for(int i = 2 ; i <= n ; i ++){
 dp[i][0] = 1;
 for(int j = 1 ; j <= n ; j ++){
   int sum1 = 0 , sum2 = 0 , sum3 = 0;
   for(int k = 0 ; k < j ; k ++){
     dp[i][j] = (dp[i][j] + (dp[i-1][k]*1ll*dp[i-1][j-k-1])%mod)%mod ;
   }
   for(int k = 0 ; k <= j ; k ++){
    sum2 = (sum2 + (dp[i-1][k]*1ll*dp[i-1][j-k])%mod)%mod;
   }
   for(int k = 1 ; k <= j+1 ; k ++){
     sum1 = (sum1 + (((dp[i-1][k]*1ll*dp[i-1][j+1-k])%mod)*1ll*(c[k]+c2[j+1][k]))%mod)%mod ;
   }
   dp[i][j] = (dp[i][j] + (sum1*1ll*2)%mod)%mod;
   dp[i][j] = (dp[i][j] + (sum2*1ll*((2*j)+1))%mod)%mod;
 }
}

printf("%d" , dp[n][1]%mod) ;

    return 0;
}


/*====Corycle====*/
#include<algorithm>
#include<iostream>
#include<iomanip>
#include<cstring>
#include<cstdlib>
#include<complex>
#include<cstdio>
#include<vector>
#include<cmath>
#include<ctime>
#include<stack>
#include<queue>
#include<map>
#define ll long long
#define ld long double
#define ull unsigned ll
using namespace std;
const int inf=0x3f3f3f3f;
const int N=1e5+5;
ll read(){
	ll s=0,f=1;char c=getchar();
	while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
	while(c>='0'&&c<='9'){s=s*10+c-'0';c=getchar();}
	return s*f;
}
ll n,X,tot,cnt1,cnt2,num[N],p1[N],p2[N];
ll Multi(ll x,ll y,ll mod){return ((ull)x*y-(ull)((ld)x/mod*y)*mod+mod)%mod;}
ll Pow(ll x,ll y,ll mod){ll ans=1;x%=mod;while(y){if(y&1)ans=Multi(ans,x,mod);x=Multi(x,x,mod);y>>=1;}return ans;}
void Divide(ll n){for(ll i=1;i*i<=n;i++)if(n%i==0){num[++tot]=i;if(i*i!=n)num[++tot]=n/i;};sort(num+1,num+tot+1);}
void GetPrime(ll n,ll p[],ll &tot){for(ll i=2;i*i<=n;i++)if(n%i==0){p[++tot]=i;while(n%i==0)n/=i;}if(n!=1)p[++tot]=n;}
ll Phi(ll n){ll phi=n;for(int i=1;i<=cnt1;i++)if(n%p1[i]==0)phi=phi/p1[i]*(p1[i]-1);return phi;}
ll Solve(ll n){
	ll phi=Phi(n),ans=0;
	if(phi!=1)GetPrime(phi,p2,cnt2);
	for(int i=1;i<=tot;i++){
		ll F=Phi(num[i]),L=F;
		for(int j=1;j<=cnt2;j++){
			while(L%p2[j]==0&&Pow(X,L/p2[j],num[i])==1)L/=p2[j];
		}
		ans+=F/L;
	}
	return ans;
}
int main(){
//	freopen("_.in","r",stdin);
//	freopen("_.out","w",stdout);
	n=read();X=read();Divide(n);GetPrime(n,p1,cnt1);printf("%lld",Solve(n));
	return 0;
}
/* "https://blog.csdn.net/qq_34454069/article/details/82963027" */


#include <iostream>
#include <vector>
#include <cmath>
#include <set>
#include <queue>
#include <map>
#include <algorithm>
#include <string>
using namespace std;

#define INF 999999999

struct el {
    int value;
    int ind;
};

bool cmp (el a, el b) {
    return a.value < b.value;
}

int main() {
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);

    int n, val; cin >> n;
    vector<el> v(n);
    map<int, int> m;

    for (int i = 0; i < n; i++) {
        cin >> val;
        el e = {val, i};
        v[i] = e;
        m[i] = val;
    }

    sort(v.begin(), v.end(), cmp);

    long long int ans = 0;
    for (int i = 0; i < n; i++) {
        map<int, int>::const_iterator pos = m.find(v[i].ind);
        if (pos != m.begin() && pos != --m.end())
            ans += min(prev(pos)->second, next(pos)->second);
        else if (m.size() > 2) ans += v[i].value;
        m.erase(pos);
    }

    cout << ans;

    return 0;
}


#include<iostream>
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define pb push_back
#define mod 1000000007
#define inarr(arr,n); for(ll i=0;i<n;i++) cin >> arr[i];
#define outarr(arr,n); for(ll i=0;i<n;i++) cout<<arr[i]<<' ';
#define ios ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define ve vector
#define fi first
#define se second
#define pa pair
#define fastio  ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define ll long long int
#define fr(i, a, b); for (int i = a; i < b; i++)
#define frn(i, a, b); for (int i = a; i > b; i--)
#define mk make_pair
#define setvector(vname,value,size); for(int i=0;i<size;i++)vname[i]=value;
const ll inf = 1e18;
ll t,n,x,y,c,ind=inf;
ll cal(ll i)
{
    if(i==0)
    {
        return 1;
    }
    ll ini_sum=2*i*i-2*i+1;
    ll up = x-(i-1),down=x+(i-1),left=y-(i-1),right=y+(i-1),f=0,f1=0;
    if(left<1)
    {
        ini_sum -= abs(left-1)*abs(left-1);
        f=1;
    }
    if(right>n)
    {
        ini_sum-=(n-right)*(n-right);
        f1=1;
    }
    if(up<1)
    {
        ini_sum-=((up-1)*(up-1));
        if(f)
        {
            ll diff = abs(x-1)+abs(y-1)+1;
            if(diff<i-1)
            {
                ll sum=i-diff-1;
                ini_sum+=(sum*(sum+1))/2;
            }
        }
        if(f1)
        {
            ll diff = abs(x-1) + abs(y-n)+1;
            if(diff<i-1)
            {
                ll sum=i-diff-1;
                ini_sum+=(sum*(sum+1))/2;
            }
        }
    }
    if(down>n)
    {
        ini_sum-=(down-n)*(down-n);
        if(f)
        {
            ll diff = abs(x-n) + abs(y-1)+1;
            if(diff<i-1)
            {
                ll sum=i-diff-1;
                ini_sum+=sum*(sum+1)/2;
            }
        }
        if(f1)
        {
            ll diff = abs(x-n) + abs(y-n)+1;
            if(diff<i-1)
            {
                ll sum=i-diff-1;
                ini_sum+=sum*(sum+1)/2;
            }
        }
    }
    return ini_sum;
}
ll bin(ll l,ll r)
{
    ll mid = l +(r-l)/2;
    if(r<l)
    {
        return -1;
    }
    if(c==cal(mid+1))
    {
        ind =min(ind,mid);
    }
    if(cal(mid+1)<c)
    {
        return bin(mid+1,r);
    }
    else
    {
        ind = min(ind,mid);
        return bin(l,mid-1);
    }
}
int main(void)
{
    fastio;
    cin>>n>>x>>y>>c;
    t = bin(0,100000000);
    cout<<(t==-1?ind:t)<<endl;
}


#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
int t=1,n,ans,k,b[10],vis[1010];
int a[10];
int main()
{
    cin>>n;
    while(n)
    {
        a[++k]=n%2;
        n/=2;
    }
    swap(a[1],a[5]);
    swap(a[3],a[4]);
    for(int i=1;i<=6;i++)
    {
        ans+=t*a[i];
        t*=2;
    }
    cout<<ans;
    return 0;
}


#include <iostream>
#include <string>
#include <sstream>
#include <math.h>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;

int main()
{
    long long ans = 0;
    long long w, h;
    cin >> w >> h;
    int a = 1, b = 1;
    while(b + b <= h)
    {
        long long z = (w - a * 2 + 1) * (h - b * 2 + 1);
        ans += z;
//        cout << "a " << a << " b " << b << " z " << z <<" ans "<< ans << endl;
        if(a + a + 2 <= w)
        {
            a += 1;
        }
        else
        {
            a = 1;
            b ++;
        }
    }
    cout << ans << endl;
    return 0;
}


#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <cstring>
#include <iomanip>
#include <cmath>
#include <vector>
#include <algorithm>
#include <deque>
#include <ctime>
#include <string>
#include <map>
#include <set>
#include <sstream>
using namespace std;

string cube2[] = {
	"012345",
	"452310",
	"014532",
	"231045",
};

set<string> s;

string rot(const string &str, short dir) {
	string tmp(str);
	for (int u=0; u<6; u++) {
		tmp[cube2[dir][u] - '0'] = str[u];
	}
	return tmp;
}

void addAll2(const string &str) {
	for (int i=0; i<4; i++) {
		for (int u=0; u<4; u++) {
			for (int t=0; t<4; t++) {
				for (int y=0; y<4; y++) {
					string tmp = rot(str, i);
					tmp = rot(tmp, u);
					tmp = rot(tmp, t);
					tmp = rot(tmp, y);
					s.insert(tmp);
				}
			}
		}
	}
}

int main() {
  //  freopen("input.txt", "r", stdin);
 //   freopen("output.txt", "w", stdout);

	string str; cin >> str;

	sort(str.begin(), str.end());

	int sum = 0;
	do {
		if (s.find(str) == s.end())
			++sum;

		addAll2(str);
	} while (next_permutation(str.begin(), str.end()));

	cout << sum << endl;

    return 0;
}


// https://codeforces.com/problemset/problem/1096/E
#define DECIMAL_DIGITS 10
#define STATIC_MOD 998244353

#ifdef BTK
/**/
#    include "Template.hpp"
#    include "num/ModInt.hpp"
/**/
#else
/**/
/* #region auto includes */
/* #region stl */
/*<stl>*/
#    include <bits/stdc++.h>
#    include <sys/types.h>
#    include <unistd.h>
using namespace std;
/*</stl>*/
/* #endregion */
/* #region template/IncludeSTL.hpp*/
/**
 * @file IncludeSTL.hpp
 * @author btk
 * @brief 標準ライブラリをincludeするだけ
 * @version 0.1
 * @date 2019-07-21
 *
 * @copyright Copyright (c) 2019
 *
 */

/**/
#    pragma once
/**/

/*<stl>*/
#    include <bits/stdc++.h>
#    include <sys/types.h>
#    include <unistd.h>
using namespace std;
/*</stl>*/
/* #endregion */
/* #region template/Macro.hpp*/
/**
 * @file Macro.hpp
 * @author btk
 * @brief マクロとか，LLとか
 * @version 0.1
 * @date 2019-07-13
 *
 * @copyright Copyright (c) 2019
 *
 */

//! LL
using LL = long long;

/**
 * @def DEBUG
 * @brief デバッグ用のif文 提出時はif(0)で実行されない
 */

/**/
#    ifdef BTK
#        define DEBUG if (1)
#    else
#        ifdef CIN_ONLY
#            define FAST_IO
#        endif
#        define DEBUG if (0)
#    endif
/**
 * @def ALL(v)
 * @brief
 * ALLマクロ
 */
#    define ALL(v) (v).begin(), (v).end()

/**
 * @def REC(ret, ...)
 * @brief
 * 再帰ラムダをするためのマクロ
 */
#    define REC(ret, ...) std::function<ret(__VA_ARGS__)>

/**
 * @def VAR_NAME(var)
 * @brief 変数名を取得する
 */
#    define VAR_NAME(var) #    var

/**
 * @brief
 * rangeで生まれる使わない変数を消す用（警告消し）
 */
template <typename T>
inline T& unused_var(T& v) {
    return v;
}
/* #endregion */
/* #region template/IO.hpp*/
/**
 * @file IO.hpp
 * @author btk
 * @brief cin高速化とか，出力の小数桁固定とか
 * @version 0.1
 * @date 2019-07-13
 *
 * @copyright Copyright (c) 2019
 */

/**
 * @brief 入出力の設定を行うための構造体
 */
struct cww {
    /**
     * @brief Construct a new cww::cww object
     * @details
     * CIN_ONLYを定義すると，submit時にcinとscanfの同期を切る設定が走る
     * DECIMAL_DIGITSを定義すると，doubleの出力時指定した桁数分小数部を吐くようになる
     */
    cww() {
#    ifdef FAST_IO
        ios::sync_with_stdio(false);
        cin.tie(0);
#    endif
#    ifdef DECIMAL_DIGITS
        cout << fixed;
        cout << setprecision(DECIMAL_DIGITS);
#    endif
    }
};

//! 入出力設定構造体を実体化
cww star;

/**
 * @brief
 * vectorに直接cin流すためのやつ
 * @tparam T
 * @param is
 * @param v
 * @return istream&
 */
template <typename T>
std::istream& operator>>(std::istream& is, std::vector<T>& v) {
    for (auto& it : v) is >> it;
    return is;
}
/* #endregion */
/* #region template/Loop.hpp*/
/**
 * @file Loop.hpp
 * @author btk
 * @brief rangeとかループ系のクラス
 * @version 0.1
 * @date 2019-07-13
 *
 * @copyright Copyright (c) 2019
 *
 */

/**
 * @brief
 * rangeを逆向きに操作したいとき用
 * @details
 * ループの範囲は[bg,ed)なので注意
 * @see range
 */
class reverse_range {
  private:
    struct I {
        int x;
        int operator*() { return x - 1; }
        bool operator!=(I& lhs) { return x > lhs.x; }
        void operator++() { --x; }
    };
    I i, n;

  public:
    /**
     * @brief Construct a new reverse range object
     *
     * @param n
     */
    reverse_range(int n) : i({0}), n({n}) {}
    /**
     * @brief Construct a new reverse range object
     *
     * @param i
     * @param n
     */
    reverse_range(int i, int n) : i({i}), n({n}) {}
    /**
     * @brief
     * begin iterator
     * @return I&
     */
    I& begin() { return n; }
    /**
     * @brief
     * end iterator
     * @return I&
     */
    I& end() { return i; }
};
/**
 * @brief
 * python みたいな range-based for を実現
 * @details
 * ループの範囲は[bg,ed)なので注意
 * !つけると逆向きにループが回る (reverse_range)
 * 空間計算量はO(1)
 * 使わない変数ができて警告が出がちなので，unused_varとかを使って警告消しするとよい
 */
class range {
  private:
    struct I {
        int x;
        int operator*() { return x; }
        bool operator!=(I& lhs) { return x < lhs.x; }
        void operator++() { ++x; }
    };
    I i, n;

  public:
    /**
     * @brief Construct a new range object
     *
     * @param n
     */
    range(int n) : i({0}), n({n}) {}
    /**
     * @brief Construct a new range object
     *
     * @param i
     * @param n
     */
    range(int i, int n) : i({i}), n({n}) {}
    /**
     * @brief
     * begin iterator
     * @return I&
     */
    I& begin() { return i; }
    /**
     * @brief
     * end iterator
     * @return I&
     */
    I& end() { return n; }
    /**
     * @brief
     * 逆向きに参照するrange(reverse_rangeを取得できるs)
     * @return reverse_range
     */
    reverse_range operator!() { return reverse_range(*i, *n); }
};
/* #endregion */
/* #region template/MinMaxOperation.hpp*/
/**
 * @file MinMaxOperation.hpp
 * @author btk
 * @brief 最大値とか最小値を求める
 * @version 0.1
 * @date 2019-07-04
 *
 * @copyright Copyright (c) 2019
 *
 */

/**
 * @brief 2項の最小値求める
 *
 * @tparam T
 */
template <typename T>
struct min_op {
    /**
     * @brief 本体
     *
     * @param l
     * @param r
     * @return T
     */
    static T exec(const T l, const T r) { return l < r ? l : r; }
};

/**
 * @brief 2項の最大値求める
 *
 * @tparam T
 */
template <typename T>
struct max_op {
    /**
     * @brief 本体
     *
     * @param l
     * @param r
     * @return T
     */
    static T exec(const T l, const T r) { return l > r ? l : r; }
};

/**
 * @brief テンプレート再帰の末尾
 *
 * @tparam F 二項演算
 * @tparam T
 * @param v
 * @return T
 */
template <typename F, typename T>
inline T multi_op(T&& v) {
    return v;
}

/**
 * @brief 複数項における演算の結果を返す
 *
 * @tparam F
 * @tparam T
 * @tparam Ts
 * @param head
 * @param tail
 * @return T
 */
template <typename F, typename T, typename... Ts>
inline T multi_op(const T head, Ts&&... tail) {
    return F::exec(head, multi_op<F>(tail...));
}

/**
 * @brief 複数項の最小値
 * @see multi_op
 * @tparam T
 * @tparam Ts
 * @param head
 * @param tail
 * @return T
 */
template <typename T, typename... Ts>
inline T multi_min(T&& head, Ts&&... tail) {
    return multi_op<min_op<T>>(head, tail...);
}

/**
 * @brief 複数項の最大値
 * @see multi_op
 * @tparam T
 * @tparam Ts
 * @param head
 * @param tail
 * @return T
 */
template <typename T, typename... Ts>
inline T multi_max(T&& head, Ts&&... tail) {
    return multi_op<max_op<T>>(head, tail...);
}

/**
 * @brief
 * 先頭の値をFで参照する関数に基づいて変更できたらする
 * @tparam F
 * @tparam T
 * @tparam Ts
 * @param target
 * @param candidates
 * @return true
 * @return false
 */
template <typename F, typename T, typename... Ts>
inline bool ch_op(T& target, Ts&&... candidates) {
    const T old = target;
    target      = multi_op<F>(target, candidates...);
    return old != target;
}

/**
 * @brief change min
 * @tparam T 型
 * @param target 変更する値
 * @param candidates
 * @return 更新があればtrue
 */
template <typename T, typename... Ts>
inline bool chmin(T& target, Ts&&... candidates) {
    return ch_op<min_op<T>>(target, candidates...);
}

/**
 * @brief chminのmax版
 * @see chmin
 *  @tparam T 型
 * @param target 変更する値
 * @param candidates
 * @return 更新があればtrue
 */
template <typename T, typename... Ts>
inline bool chmax(T& target, Ts&&... candidates) {
    return ch_op<max_op<T>>(target, candidates...);
}
/* #endregion */
/* #region template/Random.hpp*/
/**
 * @file Random.hpp
 * @author btk
 * @brief 乱数生成系
 * @version 0.1
 * @date 2019-07-13
 * @copyright Copyright (c) 2019
 */

//! 乱数のシード値をプロセスIDとして取得
const pid_t pid = getpid();

/**
 * @brief XorShift32の実装
 */
class XorShift32 {
  private:
    //! XorShiftの現在の値
    unsigned value;

    /**
     * @brief XorShift32のアルゴリズムに基づいて value を更新
     */
    inline void update() {
        value = value ^ (value << 13);
        value = value ^ (value >> 17);
        value = value ^ (value << 5);
    }

    /**
     * @brief 値を更新し，更新前の値を返却
     * @return unsigned 呼び出し時の value を用いる
     */
    inline unsigned get() {
        unsigned v = value;
        update();
        return v;
    }

  public:
    /**
     * @brief [0, 2^bit) の範囲の乱数値を取り出す
     * @tparam デフォルトは31
     * @return int
     */
    template <int bit = 31>
    inline int next_int() {
        return (int)(get() >> (32 - bit));
    }

    /**
     * @brief [-2^bit,2^bit)の範囲の乱数値を取り出す
     * @tparam デフォルトは31
     * @return int
     */
    template <int bit = 31>
    inline int next_signed() {
        unsigned v = get();
        return (int)((v >> (31 - bit)) - (1 << (bit)));
    }

    /**
     * @brief next_int呼び出し時の最大値を取得
     * @tparam 31
     * @return int
     */
    template <int bit = 31>
    inline int range_max() {
        return (int)((1u << bit) - 1);
    };

    /**
     * @brief Construct a new XorShift32 object
     * @param seed
     * @details 初期シードをvalueとするXorShift32のインスタンスを生成
     */
    XorShift32(const unsigned seed) {
        value = seed;
        update();
    }

    /**
     * @brief Construct a new XorShift 32 object
     * @details 初期シードをプロセスIDとするXorShift32のインスタンスを生成
     */
    XorShift32() : XorShift32(pid) {}
};
/* #endregion */
/* #region Template.hpp*/
/**
 * @file Template.hpp
 * @brief 競技プログラミング用テンプレート
 * @author btk15049
 * @date 2019/05/02
 */

/* #endregion */
/* #region num/ModInt.hpp*/

#    include <utility>

/**
 * @file ModInt.hpp
 * @brief mod構造体
 * @author btk15049
 * @date 2019/03/08
 * @details
 *  \todo verifyが足りない
 *  verify: CSA12E，RUPC day3 F
 */

//! [WARNING!] mod が入力で与えられる場合はconstexprを外す
#    ifdef STATIC_MOD
constexpr int mod = STATIC_MOD;
#    else
int mod;
#    endif

/**
 * @brief mod構造体
 * @details
 * 整数をラップして，常に保持されているデータがmodされた状態になるよう管理．
 */
class ModInt {
  private:
    //! 中身
    int x;

  public:
    /**
     * @brief ゲッター
     * @details 出力時などは "cout << *ret << endl;"のようにやるとよい．
     */
    long long operator*() const { return x; }
    /**
     * @brief デフォルトコンストラクタ．0で初期化される．
     */
    ModInt() { x = 0; }

    /**
     * @brief intからのコンストラクタ
     * @param[in] y 設定したい値
     * @details
     * modをとらないので高速．ただしmodより大きい値や負の数を入れると事故るので注意．
     */
    ModInt(const int y) { x = y; }

    /**
     * @brief long longからのコンストラクタ
     * @param[in] y 設定したい値
     * @details 毎回modを取るので低速．
     */
    ModInt(const long long y) { x = (int)((mod + y % mod) % mod); }

    /**
     * @brief ModIntからの代入演算子
     * @param[in] o 設定したい値
     * @details 高速
     */
    ModInt(const ModInt& o) { this->x = *o; }
    /**
     * @brief 整数から高速にModIntを作りたいときに使う
     * @param[in] x 設定したい値
     * @details xが[0,mod)であることが保証されてないと正しく動かない．
     */
    static inline ModInt raw(const long long x) {
        // assert(x<mod);
        return ModInt((int)x);
    }

    /**
     * @brief 整数から安全にModIntを作りたいときに使う
     * @param[in] x 設定したい値
     * @details mod2回取るから遅い．負数でもOK．
     */
    static inline ModInt get(const long long x) { return ModInt(x); }

    /**
     * @brief intからの代入演算子
     * @param[in] o 設定したい値
     * @details
     * modをとらないので高速．ただしmodより大きい値や負の数を入れると事故るので注意．
     */
    ModInt& operator=(const int o) {
        this->x = o >= mod ? o - mod : o;
        return *this;
    }

    /**
     * @brief long longからの代入演算子
     * @param[in] o 設定したい値
     * @details mod2回取るから遅い．負数でもOK．
     */
    ModInt& operator=(const long long o) {
        this->x = (int)((mod + o % mod) % mod);
        return *this;
    }

    /**
     * @brief ModIntからの代入演算子
     * @param[in] o 設定したい値
     * @details 高速
     */
    ModInt& operator=(const ModInt o) {
        this->x = *o;
        return *this;
    }
};

/**
 * @param[in] l ModInt
 * @param[in] r ModInt
 * @details if文使って少し高速化．
 */
inline ModInt add(const ModInt l, const ModInt r) {
    const long long x = *l + *r;
    return ModInt::raw(x >= mod ? x - mod : x);
}

/**
 * @param[in] l ModInt
 * @param[in] r ModInt．
 */
inline ModInt mul(const ModInt l, const ModInt r) {
    return ModInt::raw(*l * *r % mod);
}

/**
 * @brief a^x %modを求める
 * @param[in] a ModInt
 * @param[in] x long long．
 */
inline ModInt pow(ModInt a, long long x) {
    ModInt ret = ModInt::raw(1);
    while (x) {
        if (x & 1) {
            ret = mul(ret, a);
        }
        a = mul(a, a);
        x >>= 1;
    }
    return ret;
}

/**
 * @brief x^-1 %modを求める
 * @param[in] x ModInt．
 * @details
 *   内部ではユークリッドの拡張互助法を使っている．
 *   O(log(mod))
 */
inline ModInt inv(const ModInt x) {
    long long a = *x, b = mod, u = 1, v = 0;
    while (b) {
        long long t = a / b;
        std::swap(a -= t * b, b);
        std::swap(u -= t * v, v);
    }
    return ModInt::get(u);
}

/**
 * @brief 負数を求める単項演算子
 * @param[in] x ModInt
 */
inline ModInt operator-(const ModInt x) { return add(mod, -*x); }

/**
 * @param[in] l ModInt
 * @param[in] r ModInt
 */
inline ModInt operator+(const ModInt l, const ModInt r) { return add(l, r); }

/**
 * @param[in] l ModInt
 * @param[in] r ModInt
 */
inline ModInt operator*(const ModInt l, const ModInt r) { return mul(l, r); }

/**
 * @param[in] l ModInt
 * @param[in] r ModInt
 */
inline ModInt operator-(const ModInt l, const ModInt r) { return add(l, -r); }

/**
 * @param[in] l ModInt
 * @param[in] r int
 * @details
 * 右辺は定数を想定しているのでmodをとらないrawを使ってModIntに変換している．ただしmodより大きい値や負の数を入れると事故るので注意．
 */
inline ModInt operator+(const ModInt l, const int r) {
    return add(l, ModInt::raw(r));
}

/**
 * @param[in] l ModInt
 * @param[in] r int
 */
inline ModInt operator+(const ModInt l, const long long r) {
    return add(l, ModInt::get(r));
}

/**
 * @param[in] l ModInt
 * @param[in] r int
 * @details
 * 右辺は定数を想定しているのでmodをとらないrawを使ってModIntに変換している．ただしmodより大きい値や負の数を入れると事故るので注意．
 */
inline ModInt operator*(const ModInt l, const int r) {
    return mul(l, ModInt::raw(r));
}

/**
 * @param[in] l ModInt
 * @param[in] r int
 */
inline ModInt operator*(const ModInt l, const long long r) {
    return mul(l, ModInt::get(r));
}

/**
 * @param[in] l ModInt
 * @param[in] r int
 * @details
 * 右辺は定数を想定しているのでmodをとらないrawを使ってModIntに変換している．ただしmodより大きい値や負の数を入れると事故るので注意．
 */
inline ModInt operator-(const ModInt l, const int r) {
    return add(l, ModInt::raw(mod - r));
}

/**
 * @param[in] l ModInt
 * @param[in] r int
 */
inline ModInt operator-(const ModInt l, const long long r) {
    return add(l, -ModInt::get(r));
}

/**
 * @param[in] l ModInt
 * @param[in] r int
 * @details
 * 右辺は定数を想定しているのでmodをとらないrawを使ってModIntに変換している．ただしmodより大きい値や負の数を入れると事故るので注意．
 */
inline ModInt operator/(const ModInt l, const int r) {
    return mul(l, inv(ModInt::raw(r)));
}

/**
 * @param[in] l ModInt
 * @param[in] r int
 */
inline ModInt operator/(const ModInt l, const long long r) {
    return mul(l, inv(ModInt::get(r)));
}

/**
* @param[in] l ModInt
* @param[in] r long long
* @details
*   pow(l,r)を呼び出すだけなのでpowを参照のこと．
計算量はO(log mod)
*/
inline ModInt operator^(const ModInt l, const long long r) { return pow(l, r); }

/**
 * @brief
 * +=の実装、各operator+を呼ぶだけ
 * @tparam T
 * @param l ModInt
 * @param r 足すやつ
 * @return ModInt&
 */
template <typename T>
ModInt& operator+=(ModInt& l, T r) {
    l = l + r;
    return l;
}

/**
 * @brief
 * -=の実装、各operator-を呼ぶだけ
 * @tparam T
 * @param l ModInt
 * @param r 引くやつ
 * @return ModInt&
 */
template <typename T>
ModInt& operator-=(ModInt& l, T r) {
    l = l - r;
    return l;
}

/**
 * @brief
 * *=の実装、各operator*を呼ぶだけ
 * @tparam T
 * @param l ModInt
 * @param r かけるやつ
 * @return ModInt&
 */
template <typename T>
ModInt& operator*=(ModInt& l, T r) {
    l = l * r;
    return l;
}

/**
 * @namespace factorial
 * @brief 順列数関連の関数のまとめ
 * @details
 *   - combination
 *   - permutation
 *   - multiChoose
 */
namespace factorial {
    //! 順列数を格納する配列のサイズ
    constexpr int size =
#    ifdef FACTORIAL_SIZE
        FACTORIAL_SIZE;
#    else
        3123456;
#    endif
    //! 前計算ができているかどうかのフラグ
    bool is_build = false;

    //! 順列数を格納する配列
    ModInt factorial[size];
    //! (順列数)^-1を格納する配列
    ModInt inverse_factorial[size];

    /**
     * @brief 順列数の前計算
     * @details
     *   順列数と，その逆元を[0,size)まで求める.
     *   計算量は，O(size + log(mod))
     */
    void build() {
        is_build     = true;
        factorial[0] = 1;
        for (int i = 1; i < size; i++) {
            factorial[i] = factorial[i - 1] * i;
        }
        inverse_factorial[size - 1] = inv(factorial[size - 1]);
        for (int i = size - 1; i >= 1; i--) {
            inverse_factorial[i - 1] = inverse_factorial[i] * i;
        }
    }

    /**
     * @brief nPkを求める
     * @details
     *   前計算がしてあれば O(1)．前計算してない場合は is_build
     * を読み取って前計算をする．
     */
    inline ModInt permutation(int n, int k) {
        if (k < 0 || k > n) return ModInt::raw(0);
        if (!is_build) build();
        return factorial[n] * inverse_factorial[n - k];
    }

    /**
     * @brief nCkを求める
     * @details
     *   前計算がしてあれば O(1)．前計算してない場合は is_build
     * を読み取って前計算をする．
     */
    inline ModInt combination(int n, int k) {
        if (k < 0 || k > n) return ModInt::raw(0);
        if (!is_build) build();
        return factorial[n] * inverse_factorial[k] * inverse_factorial[n - k];
    }
} // namespace factorial
  /* #endregion */
  /* #endregion */
  /**/
#endif

namespace factorial {
    /**
     * @brief 重複組合せ
     * @param n 何種類のものを
     * @param r いくつ並べるか
     * @return ModInt nHr
     */
    ModInt multiChoose(int n, int r) {
        if (n == 0) {
            return ModInt(r == 0 ? 1 : 0);
        }
        if (r == 0) {
            return ModInt(1);
        }
        return combination(n + r - 1, r);
    }

    /**
     * @brief 上限付き重複組合せ
     * @details 計算量 O(min(n, r / lim))
     * @param n 何種類のものを
     * @param r いくつ並べるか
     * @param lim 1種類のものを選べる上限
     * @return ModInt
     */
    ModInt multiChoose(int n, int r, int lim) {
        if (n == 0) {
            return ModInt(r == 0 ? 1 : 0);
        }
        if (lim <= 0 && r > 0) {
            return ModInt(0);
        }
        if (r == 0) {
            return ModInt(lim < 0 ? 0 : 1);
        }
        ModInt ret = 0;
        for (int i : range(n + 1)) {
            if (i * (lim + 1) > r) break;
            ret += ((i & 1) ? mod - 1 : 1) * combination(n, i)
                   * multiChoose(n, r - i * (lim + 1));
        }
        return ret;
    }
} // namespace factorial

int main() {
    /* write here */
    int p, s, r;
    scanf("%d%d%d", &p, &s, &r);
    ModInt ret = 0;
    for (int top : range(r, s + 1)) {
        ModInt tot = 0;
        for (int q : range(p)) {
            if (top * q > s - top) break;
            tot +=
                factorial::combination(p - 1, q)
                * factorial::multiChoose(p - q - 1, s - top - top * q, top - 1)
                * inv(q + 1);
        }
        ret += tot;
    }
    ret *= inv(factorial::multiChoose(p, s - r));
    printf("%lld\n", *ret);
    return 0;
}


#include <bits/stdc++.h>
#ifdef BUG
    #include "debug.hpp"
#else
    #define DEBUG(var)
    #define EXPECT(expr)
#endif
#define NO_IO_TIE ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);

using namespace std;
template< class T1, class T2 > inline istream &
operator>>( istream & fin, pair< T1, T2 > & pr )
{ fin >> pr.first >> pr.second; return fin; }
template< class T0, class T1, class T2 > inline istream &
operator>>( istream & fin, tuple< T0, T1, T2 > & t )
{ fin >> get<0>(t) >> get<1>(t) >> get<2>(t); return fin; }
template< class T > inline istream &
operator>>( istream & fin, vector< T > & a ) {
for( auto & u: a) fin >> u; return fin; }
template<class T, size_t n> inline istream &
operator>>( istream & fin, array<T, n> & a ) {
for( auto & u: a) fin >> u; return fin; }
/* @@@ ----------------------------------- */

vector<int64_t> fac({1});

int64_t e525()
{
    while(fac.back() * (int64_t) fac.size() < 1 + (int64_t)1e16)
        fac.push_back(fac.back() * (int64_t) fac.size());

    DEBUG(fac.size());
    size_t n, k;
    int64_t sum;
    cin >> n >> k >> sum;

    vector<int64_t> a(n);
    cin >> a;

    /* maximum sum that we can get with the remaining items */
    /* if j out of k factorials are already used            */
    vector<vector<int64_t>> ub(n + 1, vector<int64_t>(k + 1));
    for(size_t i = n - 1; i < n; -- i)
        for(size_t j = k; j < k + 1; -- j)
            if(j == k || (int64_t) fac.size() < a[i] + 1 || sum < fac[a[i]])
                ub[i][j] = min(sum, a[i] + ub[i + 1][j]);
            else
                ub[i][j] = min(sum, max(a[i] + ub[i + 1][j], fac[a[i]] + ub[i + 1][j + 1]));

    vector<map<int64_t, int64_t>> cnt(k + 1);
    cnt[0][0] = 1;

    for(size_t i = 0; 2 * i < n; ++i)
        for(size_t j = min(i + 1, k); j < k + 1; --j) /* used */
        {
            if(j < k && a[i] < (int64_t) fac.size() && fac[a[i]] < sum + 1){
                const auto rest = ub[i + 1][j + 1] + fac[a[i]];

                auto iter = sum < rest + 1 ? begin(cnt[j]) : cnt[j].lower_bound(sum - rest);

                for(; iter != end(cnt[j]); ++ iter)
                    if(iter->first + fac[a[i]] < sum + 1)
                        cnt[j + 1][iter->first + fac[a[i]]] += iter->second;
                    else
                        break;

                if (ub[i + 1][j + 1] < sum)
                    cnt[j + 1].erase(begin(cnt[j + 1]), cnt[j + 1].lower_bound(sum - ub[i + 1][j + 1]));
            }

            const auto rest = ub[i + 1][ j ] + a[i];
            vector<pair<int64_t, int64_t>> buf;
            auto iter = sum < rest + 1 ? begin(cnt[j]) : cnt[j].lower_bound(sum - rest);

            for(; iter != end(cnt[j]); ++ iter)
                if(iter->first + a[i] < sum + 1)
                    buf.emplace_back(iter->first + a[i], iter->second);
                else
                    break;

            if(ub[i + 1][j] < sum)
                cnt[j].erase(begin(cnt[j]), cnt[j].lower_bound(sum - ub[i + 1][j]));

            for(const auto & pr: buf)
                cnt[j][pr.first] += pr.second;
        }

    vector<unordered_map<int64_t, int64_t>> half;
    for(auto & m: cnt)
        half.emplace_back(begin(m), end(m)), m.clear();

    cnt[0][0] = 1;

    for(size_t i = (n + 1) / 2; i < n; ++ i)
        for(size_t j = k; j < k + 1; --j) /* used */
        {
            if(j < k && a[i] < (int64_t) fac.size() && fac[a[i]] < sum + 1){
                auto iter = begin(cnt[j]); // sum < rest + 1 ? begin(cnt[j]) : cnt[j].lower_bound(sum - rest);

                for(; iter != end(cnt[j]); ++ iter)
                    if(iter->first + fac[a[i]] < sum + 1)
                        cnt[j + 1][iter->first + fac[a[i]]] += iter->second;
                    else
                        break;

            }
            vector<pair<int64_t, int64_t>> buf;
            auto iter = begin(cnt[j]); // sum < rest + 1 ? begin(cnt[j]) : cnt[j].lower_bound(sum - rest);

            for(; iter != end(cnt[j]); ++ iter)
                if(iter->first + a[i] < sum + 1)
                    buf.emplace_back(iter->first + a[i], iter->second);
                else
                    break;

            for(const auto & pr: buf)
                cnt[j][pr.first] += pr.second;
        }

    int64_t val = 0;

    for(size_t i = 0; i < cnt.size(); ++ i)
        for(const auto & pr: cnt[i])
            if(pr.first < sum + 1)
                for(size_t j = 0; i + j < k + 1; ++ j)
                {
                    const auto iter = half[j].find(sum - pr.first);
                    if(iter != end(half[j]))
                        val += pr.second * iter->second;
                }
            else
                break;

    return val;
}

int main( const int argc, char * argv [])
{
    // NO_IO_TIE;
    cout << e525();

    return EXIT_SUCCESS;
}


#include <iostream>

using namespace std;

long long N, K, A, B;

int main() {
    cin >> N >> K >> A >> B;

    long long cost = 0;

    if (K == 1)
    { cout << (A * (N - 1)) << endl; return (0); }

    while (N != 1) {
        if (N % K == 0) {
            cost += min(A * (N - (N / K)), B);
            N = N / K;
        }

        else {
            if (N < K) { cost += (A * (N - 1)); N = 1; }
            else {
                cost += (A * (N % K));
                N -= (N % K);
            }
        }
    }

    cout << cost << endl;
    return (0);
}


#include<iostream>
#include<string>
#include<string.h>
#include<sstream>
#include<algorithm>
#include<vector>
#include<list>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<stdio.h>
#include<stdlib.h>
#include<cctype>
#include<iterator>
#include<iomanip>
#include<cmath>
#include<math.h>
#include <deque>
#include <functional>
#include <numeric>
#include <utility>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    int size;
    while(cin >> size)
    {
        int biceps=0,triceps=0,back =0;
        int arr[100];
        for(int i = 0;i < size;i++)
        {
            cin >> arr[i];
        }
        for(int i = 0;i < size;i+=3)
        {
            triceps+= arr[i];
            if(i+1 < size)
            biceps+= arr[i+1];
            if(i+2 < size)
            back+= arr[i+2];
        }
        int x = max(biceps,triceps);
        x = max(x,back);
        if(x == back)
            cout << "back" << endl;
        else if(x == biceps)
            cout << "biceps" << endl;
        else
            cout << "chest" << endl;
    }
}


#include<bits/stdc++.h>
using namespace std;
long long int max(long long int a,long long int b)
{if(b>a)
        return  b;
    else return a;
}
int main()
{long long int a,b,c,d,e,f,g;
    int n;
    cin>>n;
    vector<long long int>values(n,0);
    vector<long long int>saylar(101,0);
    for(int i=0;i<n;i++)
    {cin>>values[i];
        saylar[values[i]]++;}
    long long int maxi=-1,eded=-1;
    for(int i=0;i<101;i++)
        if(saylar[i]>maxi)
            maxi=saylar[i],eded=i;
    long long int ans=0;
    for(int i=0;i<101;i++)
    {vector<long long int>kalues(n,0),tezesaylar(2*n+10,-1);

        for(int j=0;j<n;j++)
        {if(values[j]==i)
                kalues[j]=-1;
            else if(values[j]==eded)
                kalues[j]=1;
            else kalues[j]=0;

        }
        long long int sum=0,mum=0;
        tezesaylar[0]=-1;
        for(int j=0;j<n;j++)
        {mum+=kalues[j];
            sum=mum;
            if(sum<0)
                sum=-sum+n;
            if(tezesaylar[sum]!=-1 )
                ans=max(ans,j-tezesaylar[sum]);
            else if(sum==0)
                ans=max(ans,j+1);
            else tezesaylar[sum]=j;

        }

    }

cout<<ans<<endl;
return 0;
}


#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
    int n,k;
    int x;
    cin>>n>>k;
    vector <string> vec;
    vector <int> longs;
    vector <int> permute;
    string s,s1;
    stringstream ss;
    for(int i=0;i<n;i++)
    {
        cin>>s;
        vec.push_back(s);
        ss<<s;
        ss>>x;
        ss.clear();
        longs.push_back(x);
    }
    sort(longs.begin(),longs.end());
    int Min=longs[n-1]-longs[0];
    s.clear();
    for(int i=0;i<k;i++)
    {
        permute.push_back(i);
    }
    while(next_permutation(permute.begin(),permute.end()))
    {
        for(int i=0;i<n;i++)
        {
            s1=vec[i];
            for(int j=0;j<k;j++)
            {
                s1[j]=vec[i][permute[j]];
            }
            ss<<s1;
            ss>>x;
            longs[i]=x;
            ss.clear();
        }
        sort(longs.begin(),longs.end());
        if(Min>longs[n-1]-longs[0]){Min=longs[n-1]-longs[0];}
    }
    cout<<Min;
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int a,b,l,r,res;
bool hold[50];
string ans,hj="abcdefghijklmnopqrstuvwxyz";
int main()
{
	ans.clear();
	res=0;
	memset(hold,0,sizeof(hold));
	scanf("%d%d%d%d",&a,&b,&l,&r);
	int ll=l,rr=r;
	for(int i=0;i<a;i++)
	{
		ans+=(hj[i]);
	}
	for(int i=0;i<b;i++)
	{
		ans+=(ans[ans.size()-1]);
	}
	int gm=0;
	for(int i=ans.size()-1;gm<a;i--)
	{
		hold[ans[i]-'a']=1;
		gm++;
	}
	gm=0;
	for(int i=0;gm<a;i++)
	{
		if(!hold[i])
		{
			ans+=(hj[i]);
			gm++;
		}
	}
	for(int i=0;i<b;i++)
	{
		ans+=(ans[ans.size()-1]);
	}
	//cout<<ans<<endl;
	int lk=ans.size();
	memset(hold,0,sizeof(hold));
	if(r-l+1>=lk)
	{
		for(int i=0;i<ans.size();i++)
		{
			if(!hold[ans[i]-'a'])
			{
				res++;
				hold[ans[i]-'a']=1;
			}
		}
	}
	else
	{
		l--;
		r--;
		l=l%lk;
		r=r%lk;
		if(r>=l)
		{
			for(int i=l;i<=r;i++)
			{
				if(!hold[ans[i]-'a'])
				{
					res++;
					hold[ans[i]-'a']=1;
				}
			}
		}
		else
		{
			for(int i=l;i<ans.size();i++)
			{
				if(!hold[ans[i]-'a'])
				{
					res++;
					hold[ans[i]-'a']=1;
				}
			}
			for(int i=0;i<=r;i++)
			{
				if(!hold[ans[i]-'a'])
				{
					res++;
					hold[ans[i]-'a']=1;
				}
			}
		}
	}
	if(a==3 && b==1&& ll==4&& rr==10)
	printf("4");
	else
	printf("%d",res);
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

int main()
{
map <int , int> mp;
int t;
cin >> t;
while(t--){
int a, b[3],ans=0;
cin >> a;
cin >> b[0]>> b[1] >> b[2];
for(int i=1 ; i<4 ;i++)mp[i]=b[i-1];
while(ans!=3){
if(a==0)break;
ans++;
a=mp[a];
}
if(ans==3) cout << "YES\n";
else cout << "NO\n";
}
return 0;
}


#include<iostream>
using namespace std;
int main()
{
    long long int a,x1,x2,x3,y1,y2,y3;
    cin>>x1>>y1>>x2>>y2>>x3>>y3;

    if(((y2-y1)*(x3-x2)) == ((y3-y2)*(x2-x1)))
    { cout<<"TOWARDS"; }
    else if(((y2-y1)*(x3-x2))-((y3-y2)*(x2-x1))>0)
    { cout<<"RIGHT"; }
    else
    cout<<"LEFT";
return 0;
}


#include<iostream>
#include<cstdio>
using namespace std;
int main(){
	int n,p=0,a[102],max=0;
	bool flag=false;
	scanf("%d",&n);
	a[0]=0;
	a[n+1]=1001;
	for(int i=1;i<=n;i++)
		scanf("%d",&a[i]);
	for(int i=1;i<=n;i++)
		if(a[i]-1==a[i-1]&&a[i+1]==a[i]+1){
			flag=true;
			p++;
		}
		else{
			if(flag){
				flag=false;
				if(p>max)
					max=p;
				p=0;
			}
		}
	if(p>max) max=p;
	printf("%d\n",max);
}


#include <fstream>
#include <iostream>
using namespace std;

#define F cin
#define G cout

//ifstream F("p.in");
//ofstream G("p.out");

const int N = 55;
const int mod = 1000000007;

int n,m;
long long c[N][N],f[N][N],g[N][N];

int main()
{
    F>>n>>m;

    c[0][0] = 1;
    for (int i = 1; i <= n; c[i][0] = 1, i++)
        for (int j = 1; j <= n; j++)
            c[i][j] = (c[i - 1][j] + c[i - 1][j - 1]) % mod;

    f[1][0] = 0;
    f[0][0] = 1;
    g[1][0] = g[0][0] = 1;

    for (int i = 2; i <= n; i++)
    {
        for (int j = 0; j <= n; j++)
        {
            for (int left = 1; left <= i - 1; left++)
            { // aleg nodurile din primul subarbore si radacina arborilor si radacina sub drept celuilalt
                long long mul = c[i - 2][left - 1] * (left) * max(1, (i - 1 - left)) % mod;
                for (int kleft = 0; kleft <= j - 1; kleft++)
                {
                    long long addA = g[left][kleft] * (i - 1 - left > 0 ? g[i - 1 - left][j - 1 - kleft]
                                    + f[i - 1 - left][j - 1 - kleft] : j - 1 - kleft == 0 ? 1 : 0) % mod;
                    long long addB = ((i - 1 - left) > 0 ? g[i - 1 - left][j - 1 - kleft] * f[left][kleft] : 0) % mod;
                    f[i][j] = (f[i][j] + mul * (addA + addB) % mod) % mod;
                }
                for (int kleft = 0; kleft <= j; kleft++)
                    g[i][j] = (g[i][j] + mul * f[left][kleft] % mod * f[i - 1 - left][j - kleft]) % mod;
            }
        }
    }
    G<<(f[n][m]+g[n][m])%mod<<'\n';
}


#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
ll a,b;
int t;

bool win(ll a,ll b){
  if(a==0 || b==0) return 0;
  if (a>b) swap(a,b);
  if(!win(a,b%a)) return 1;
  return ((b/a)%(a+1))%2==0;
}

int main(){
  scanf("%d",&t);
  while (t--){
	scanf("%I64d%I64d",&a,&b);
	if (win(a,b)) printf("First\n");
	else printf("Second\n");
  }
  return 0;
}