CF1912D 题解

· · 题解

思路

通过观察数据学习小学奥数我们可以知道,若可以取后 k 位来判断,则 b^k\bmod n=0;若需要 k 位一节相加来判断,则 b^k\bmod n=1;若需要 k 位一节并且交替加减来判断,则 b^k\bmod n=n-1。如果 b^k\bmod n 已经进入循环了还没出答案,则无解。若对这三个式子有疑问则可自己手动列竖式理解。

代码

# include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int t, n, m, x;
bitset <1000005> vis;
int main () {
    ios::sync_with_stdio (0);
    cin.tie (0);
    cout.tie (0);
    cin >> t;
    while (t --) {
        cin >> m >> n;
        x = 1;
        m %= n;
        for (int i = 0; i < n; ++ i)
            vis[i] = 0;
        for (int k = 1; ! vis[x = x * (ll) m % n]; ++ k) {
            if (! x) {
                cout << "1 " << k << '\n';
                goto there;
            } else if (x < 2) {
                cout << "2 " << k << '\n';
                goto there;
            } else if (x > n - 2) {
                cout << "3 " << k << '\n';
                goto there;
            }
            vis[x] = 1;
        }
        cout << "0\n";
there:
        ;
    }
    return 0;
}