2019山东ACM省赛K题 zoj4123 Happy Equation

Happy Equation

Time Limit: 1 Second Memory Limit: 65536 KB

Little Sub has just received an equation, which is shown below, as his birthday gift.
$ a^x equiv x^a ( ext{mod } 2^p) ( Given the value of , please help Little Sub count the number of x() 1 le x le 2^p $ )which satisfies the equation.

Input

There are multiple test cases. The first line of the input contains an integer T (about 1000), indicating the number of test cases. For each test case:

The first and only line contains two integers and p ((1 leq a leq 10^9),(1 leq p leq 30) ).

Output

For each test case output one line containing one integer, indicating the answer.

Sample Input

2
6 12
8 16

Sample Output

1023
16383

比赛的时候想到了会和二进制有关系,但是没想出来具体的关系……

打表易知当a为奇数是答案为1(目前还不知道怎么证明).

(a)分解为(2^{k_1}+2^{k_2}+…+2^{k_n}(k_1<k_2<…<k_n)),则(a^x = {(2^{k_1}+2^{k_2}+…+2^{k_n})}^x),显然只要({(2^{k_1})}^x ext{mod } 2^p = 0) ,则(a^x ext{mod } 2^p = 0).即只要$k_1 *x >=p $ ,就有(a^x ext{mod } 2^p = 0)。这就需要另(x^a ext{mod}2^p=0) ,设x的最低位1为第(k_x)位,则需要满足(k_x *a>=p) ,可以求出(k_x) ,所有 (x^a equiv 0 ( ext{mod } 2^p))的x为公差为(2^{k_x}) 的等差数列。

然后再特判一下x较小时的情况就可以了。

#include "bits/stdc++.h"

using namespace std;

typedef long long ll;
ll mod;

ll powmod(ll a, ll b) {
    ll ret = 1;
    while (b) {
        if (b & 1) ret = ret * a % mod;
        a = a * a % mod;
        b >>= 1;
    }
    return ret;
}

int main() {
    //freopen("in.txt", "r", stdin);
    ll a, p;
    int _;
    cin >> _;
    while (_--) {
        cin >> a >> p;
        mod = pow(2, p);
        if (a % 2) {
            cout << 1 << endl;
            continue;
        }
        ll ans = 0;
        ll ka, xl;
        for (int i = 1; i <= 33; i++) {
            if (a & (1ll << i)) {
                ka = i;
                break;
            }
        }
        xl = (p + ka - 1) / ka;
        ll kx = (p + a - 1) / a;
        kx = pow(2, kx);
        ans = (pow(2, p) - max(xl, kx)) / kx + 1;
        for (ll i = 1; i <= p; i++) {
            if (powmod(a, i) == powmod(i, a) && powmod(a, i) != 0) ans++;
        }
        cout << ans << endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/albert-biu/p/10864882.html