Description
用 種顏色給一串長度爲 的項鍊染色,旋轉和翻轉視作一種方案,且顏色平移也視爲一種方案,問染色方案數
Input
第一行一整數 表示用例組數,每組用例輸入兩個整數
Output
輸出染色方案數,結果模
Sample Input
5
3 2
4 2
8 5
9 5
2333 333
Sample Output
2
4
5079
22017
544780894
Solution
,變換羣大小爲 ,對於旋轉和顏色平移的 個變換,若一個染色方案能夠在顏色平移爲 (即 顏色變成 顏色),旋轉平移爲 (即 位置移動到 位置)後不變,那麼從 走回 的這 個位置,其顏色必然要整數次從 變成 ,而 顏色變回 顏色至少需要 次,故這 個變換下不變的染色方案數爲
對於翻轉和顏色平移的 個變換
1. 爲奇數,那麼翻轉軸爲一個位置和一箇中點構成,此時該位置顏色不能變化,故顏色變換隻能爲恆同,在翻轉下不變的染色方案數爲
2. 爲偶數,那麼翻轉軸有兩種,第一種是連接兩個位置,此時這兩個位置顏色也不能變換,顏色變化只能爲恆同,在該類變換下不變的染色方案數爲 ;第二種是連接兩個中點,此時若 爲偶數,那麼此時顏色變換可以爲恆同也可以爲顏色平移 ,若 爲奇數則顏色變換隻能恆同,故在該類變換下不變的染色方案數爲
累加以上三個值之後除以 即可,注意 比較大所以要用 算法分解質因數
Code
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<vector>
#include<map>
#include<ctime>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<ll,int>P;
#define maxn 200001
#define mod 998244353
int mul(int x,int y)
{
ll z=1ll*x*y;
return z-z/mod*mod;
}
int add(int x,int y)
{
x+=y;
if(x>=mod)x-=mod;
return x;
}
int Pow(ll x,ll y)
{
x%=mod,y%=(mod-1);
int ans=1;
while(y)
{
if(y&1)ans=mul(ans,x);
x=mul(x,x);
y>>=1;
}
return ans;
}
ll gcd(ll a,ll b)
{
return b?gcd(b,a%b):a;
}
ll Mul(ll a,ll b,ll c)
{
return (a*b-(ll)(a/(ld)c*b+1e-3)*c+c)%c;
}
ll Pow(ll a,ll b,ll c)
{
ll ans=1;
while(b)
{
if(b&1)ans=Mul(ans,a,c);
a=Mul(a,a,c);
b>>=1;
}
return ans;
}
int cnt=12,prime[]={2,3,5,7,11,13,17,19,23,29,31,37};
bool isprime(ll x)
{
if(x==2)return 1;
if(x==1||!(x&1))return 0;
ll k=x-1,t=0;
for(;!(k&1);k>>=1)t++;
for(int i=0;i<cnt&&prime[i]<x;i++)
{
ll g=Pow(prime[i],k,x);
for(int j=0;j<t;j++)
{
ll g0=Mul(g,g,x);
if(g0==1&&g!=1&&g!=x-1)return 0;
g=g0;
}
if(g!=1)return 0;
}
return 1;
}
vector<ll>pf;
vector<P>fact;
ll F(ll t,ll x,ll c)
{
return (Mul(t,t,x)+c)%x;
}
void pollardRho(ll x)
{
if(isprime(x))
{
pf.push_back(x);
return;
}
while(1)
{
ll c=rand()%(x-1)+1,p=rand()%x,q=F(p,x,c);
while(p!=q)
{
ll d=gcd(x,abs(p-q));
if(d!=1)
{
pollardRho(d);
pollardRho(x/d);
return;
}
p=F(p,x,c);q=F(F(q,x,c),x,c);
}
}
}
void Deal(ll x)
{
pf.clear();
fact.clear();
pollardRho(x);
sort(pf.begin(),pf.end());
for(int i=0;i<pf.size();i++)
{
int temp=1;
while(i<pf.size()-1&&pf[i]==pf[i+1])i++,temp++;
fact.push_back(P(pf[i],temp));
}
}
int T,ans;
ll n,m;
void dfs(int pos,ll d,ll phi)
{
if(pos==fact.size())
{
ans=add(ans,mul(mul(phi%mod,Pow(m,n/d)),gcd(d,m)%mod));
return ;
}
dfs(pos+1,d,phi);
ll x=fact[pos].first;
d*=x,phi*=x-1;
for(int i=1;i<=fact[pos].second;i++)
{
dfs(pos+1,d,phi);
d*=x,phi*=x;
}
}
int main()
{
srand(time(0));
scanf("%d",&T);
while(T--)
{
scanf("%lld%lld",&n,&m);
Deal(n);
ans=0;
if(n&1)ans=mul(n%mod,Pow(m,n/2+1));
else
{
ans=mul(n/2%mod,Pow(m,n/2+1));
ans=add(ans,mul(mul(gcd(m,2),n/2%mod),Pow(m,n/2)));
}
dfs(0,1,1);
ans=mul(ans,Pow(mul(2,mul(n%mod,m%mod)),mod-2));
printf("%d\n",ans);
}
return 0;
}