Law of Commutation HDU - 6189(推导)

As we all know, operation ”+” complies with the commutative law. That is, if we arbitrarily select two integers a and b, a+b always equals to b+a. However, as for exponentiation, such law may be wrong. In this problem, let us consider a modular exponentiation. Give an integer m=2n and an integer a, count the number of integers b in the range of [1,m] which satisfy the equation abba(mod m). a b ≡ b a ( m o d   m ) .
Input
There are no more than 2500 test cases.

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

For all test cases, you can assume that n30,1a109. n ≤ 30 , 1 ≤ a ≤ 10 9 .
Output
For each test case, output an integer denoting the number of b.
Sample Input
2 3
2 2
Sample Output
1
2
回归日,哒哒~
观察发现当a为奇数时答案均为1。
当a为偶数时:
则记:

a=2y a = 2 y

则:
ab=2byb a b = 2 b y b

因为n<30,所以当 b<n b < n 时,计算机暴力验证
b>=n b >= n ,易知
ab0(mod 2n) a b ≡ 0 ( m o d   2 n )

现在看 ba b a ,易知
b=2xy b = 2 x y

ba=2xaya b a = 2 x a y a

xa>=n x a >= n 均满足。

#include<iostream>
#include<cstdio>
#include<set>
using namespace std;
long long P(long long a,long long b,long long mod)
{
    long long ans=1;
    while(b)
    {
        if(b&1)ans=ans*a%mod;
        a=a*a%mod;
        b>>=1;
    }
    return ans;
}
long long p(long long a,long long b)
{
    long long ans=1;
    while(b)
    {
        if(b&1)ans*=a;
        a*=a;
        b>>=1;
    }
    return ans;
}
int main()
{
    long long a,n;
    while(scanf("%lld%lld",&n,&a)==2)
    {
        if(a&1)cout<<1<<endl;
        else
        {
            long long m=1;
            for(int i=0;i<n;i++)
                m*=2;
            long long ans=0;
            for(int i=1;i<n;i++)
                if(P(a,i,m)==P(i,a,m))ans++;
            //cout<<"ans1: "<<ans<<endl;
            long long now=1;
            for(int i=1;i<=n;i++)
            {
                now*=2;
                if(i*a>=n)
                {
                    //cout<<"i*a: "<<i*a<<endl;
                    long long temp=1;
                    for(;;)
                    {
                        if(temp*now<n)ans--,temp+=2;
                        else break;
                    }//可能包含了前面暴力的部分,所以需要减掉
                    long long res=p(2,n-i);
                    if(res>1)ans+=res/2;
                    else ans++;
                }
            }
            cout<<ans<<endl;
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值