Happy Equation
Little Sub has just received an equation, which is shown below, as his birthday gift.
$ a^x \equiv x^a (\text{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 \text{mod } 2^p = 0\) ,則\(a^x \text{mod } 2^p = 0\).即只要$k_1 *x >=p $ ,就有\(a^x \text{mod } 2^p = 0\)。這就需要另\(x^a \text{mod}2^p=0\) ,設x的最低位1為第\(k_x\)位,則需要滿足\(k_x *a>=p\) ,可以求出\(k_x\) ,所有 \(x^a \equiv 0 (\text{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;
}