Law of Commutation HDU - 6189 思维+数学

As we all know, operation ''+'' complies with the commutative law. That is, if we arbitrarily select two integers aa and bb, a+ba+b always equals to b+ab+a. However, as for exponentiation, such law may be wrong. In this problem, let us consider a modular exponentiation. Give an integer m=2nm=2n and an integer aa, count the number of integers bb in the range of [1,m][1,m] which satisfy the equation ab≡baab≡ba (mod mm).

Input

There are no more than 25002500 test cases. 

Each test case contains two positive integers nn and a seperated by one space in a line. 

For all test cases, you can assume that n≤30,1≤a≤109n≤30,1≤a≤109.

Output

For each test case, output an integer denoting the number of bb. 

Sample Input

2 3
2 2

Sample Output

1
2

题意:给定n,a,其中2^n=m,求区间[1,m]内有多少个b满足,a^b%m=b^a%m。

思路:我们很容易知道,当a为奇数时,b一定为奇数,a为偶数时,b也一定是偶数,因此我们分为奇偶讨论。

1.奇数情况下:我们通过打表发现只有当a==b时,才可能满足a^b%m=b^a%m,因此奇数情况下只有1个b满足条件

2.偶数情况下:

① 当b>=n时,a^b可以化为(2^b)*((a/2)^b),因为b>=n,所以a^b=0 mod m 是一定成立的,则有

b^a=0 mod m,由此我们知道,b^a是2^n的倍数,则b是2^(n/a)的倍数,我们要求当b>=n时满足题意的b,即求满足

条件的[n,2^n]中2^(n/a)的倍数,则在这种情况下有m/(2^(n/a))-n/(2^(n/a))个数满足条件  (n/a向上取整)

②当b<n时,观察到n非常小,我们可以直接暴力求解

#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long ll;
ll qpow(ll a,ll n)
{
    ll ans=1;
    while(n)
    {
        if(n&1)
			ans*=a;
        a*=a;
        n/=2;
    }
    return ans;
}
ll qqpow(ll a,ll n,ll mod)
{
    ll ans=1;
    while(n)
    {
        if(n&1)
			ans=ans*a %mod;
        a=a*a %mod;
        n/=2;
    }
    return ans;
}
int main()
{
	ll n,a;
    while(~scanf("%lld%lld",&n,&a))
    {
        if (a%2)
        {
            printf("1\n");
            continue;
        }
        else
        {
            ll m=1<<n;
            ll ans=0;
            for(ll i=2;i<=n;i+=2)
                if(qqpow(a,i,m)==qqpow(i,a,m)) ans++;
            ll tmp=n/a;
            if(n%a) tmp++;
            ans+=(m/qpow(2,tmp)-n/qpow(2,tmp));
            printf("%lld\n",ans);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/why932346109/article/details/89185183
今日推荐