题解:P10515 转圈
chenly8128 · · 题解
分析一下看似复杂的移动过程。
从
题目要我们求开始循环前共走了几个格子。由于我们是从一号节点出发的,所以需要求
这就是求
由于
复杂度预处理
// Author: chenly8128
// Created: 2025-02-25 20:37:35
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 1e7;
int sf[MAXN+10],T,n,m;
vector <int> pr;
ll qpow (ll a,ll k,ll mod) {
ll ans = 1;
while (k) {
if (k&1) ans = ans * a % mod;
a = a * a % mod;
k >>= 1;
}
return ans;
}
int main (void) {
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
sf[1] = 1;
for (int i = 2;i <= MAXN;i++) {
if (!sf[i]) {
sf[i] = i;
pr.push_back(i);
}
for (int j : pr) {
if (i * j > MAXN) break;
sf[i*j] = j;
if (i % j == 0) break;
}
}
cin >> T;
while (T--) {
cin >> n >> m;
if (n == m+1) {
cout << 2 << '\n';
continue;
}
int x = n-1,ans = n-1;
while (x > 1) {
if (qpow(m+1,ans/sf[x],n) == 1) ans /= sf[x];
x /= sf[x];
}
cout << ans << '\n';
}
return 0;
}