n Complexity theory, some functions are nearly O(1)O(1), but it is greater then O(1)O(1). For example, the complexity of a typical disjoint set is O(nα(n))O(nα(n)). Here α(n)α(n) is Inverse Ackermann Function, which growth speed is very slow. So in practical application, we often assume α(n) \le 4α(n)≤4.

However O(α(n))O(α(n)) is greater than O(1)O(1), that means if nn is large enough, α(n)α(n) can greater than any constant value.

Now your task is let another slowly function log*log∗ xx reach a constant value bb. Here log*log∗ is iterated logarithm function, it means “the number of times the logarithm function iteratively applied on xx before the result is less than logarithm base aa”.

Formally, consider a iterated logarithm function log_{a}^*loga∗​ 

Find the minimum positive integer argument xx, let log_{a}^* (x) \ge bloga∗​(x)≥b. The answer may be very large, so just print the result xx after mod mm.

Input

The first line of the input is a single integer T(T\le 300)T(T≤300) indicating the number of test cases.

Each of the following lines contains 33 integers aa , bb and mm.

1 \le a \le 10000001≤a≤1000000

0 \le b \le 10000000≤b≤1000000

1 \le m \le 10000001≤m≤1000000

Note that if a==1, we consider the minimum number x is 1.

Output

For each test case, output xx mod mm in a single line.

Hint

In the 4-th4−th query, a=3a=3 and b=2b=2. Then log_{3}^* (27) = 1+ log_{3}^* (3) = 2 + log_{3}^* (1)=3+(-1)=2 \ge blog3∗​(27)=1+log3∗​(3)=2+log3∗​(1)=3+(−1)=2≥b, so the output is 2727 mod 16 = 1116=11.

样例输入复制

5
2 0 3
3 1 2
3 1 100
3 2 16
5 3 233

样例输出复制

1
1
3
11
223

不明白这道提为什么过的人不多

可能就是大家没想到在看k<m的情况下a^k%mod==a^(k%phi(m)+phi(m))是不一定成立的

所以我们在进行取余的时候就加入一些其他的操作

剩下的就是标准的递归求法了

#include<bits/stdc++.h>
using namespace std;
long long MOD(long long a,long long b) {return a<b?a:a%b+b;}
long long euler(long long n)
{
    long long res=n,a=n;
    for(long long i=2; i*i<=a; i++)
    {
        if(a%i==0)
        {
            res=res/i*(i-1);//先进行除法是为了防止中间数据的溢出
            while(a%i==0) a/=i;
        }
    }
    if(a>1) res=res/a*(a-1);
    return res;
}
long long q_p(long long a,long long b,long long mod)
{
    long long ans=1;
    while(b)
    {
        if(b%2) ans=MOD((ans*a),mod);
        b/=2;
        a=MOD(a*a,mod);
    }
    return ans;
}
long long solve(long long a,long long b,long long mod)//头上有几个b
{
    long long phi=euler(mod);
    if(b==0||mod==1)
    {
        return MOD(a,mod);
    }
    return q_p(a,solve(a,b-1,phi),mod);
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        long long a,b,mod;
        scanf("%lld%lld%lld",&a,&b,&mod);
        if(mod==1) puts("0");
        else if(b==0) puts("1");
        else printf("%lld\n",solve(a,b-1,mod)%mod);
    }
}