这道题的核心在于通过数学推导和打表发现规律,避免直接计算巨大的阶乘。以下是解题重点:
1. 基础判断
首先检查 是否能被 整除。如果不能整除,或者 ,答案直接为 。因为珠子必须用完,且任何数模 都是 。
2. 核心规律
设 ,即项链的数量。根据 是质数还是合数,分为两种情况:
情况一: 是质数
此时答案只与 的奇偶性有关:
如果 是奇数,答案为 。
如果 是偶数,答案为 。
原理简述:这是基于威尔逊定理在组合数中的推广性质。
情况二: 是合数
绝大多数情况下答案为 ,只有一个特例:
当且仅当 且 时,答案为 。
其他所有合数情况:答案均为 。
原理简述:
对于大于 的合数 , 必然能被 整除,导致基础项为 。随着 k 增大,分子中的因子更多,结果依然保持为 。只有 时, ,模 余 是非零的唯一合数特例。
以下是代码参考
#include <iostream>
using namespace std;
#define ll long long
bool is_prime(ll n){
if (n<2)
return 0;
if (n==2||n==3)
return true;
if (n%2==0||n%3==0)
return 0;
for (ll i=5;i*i<=n;i+=6){
if(n%i==0||n%(i+2)==0)
return 0;
}
return 1;
}//素数判断
void solve(){//solve()函数是推导出来的规律
ll n,m;
cin>>n>>m;
if(n%m!=0){
cout<<0<<endl;
return;
}
ll k=n/m;
if(m==1){
cout<<0<<endl;
return;
}
if(is_prime(m)){//判断素数
if(k%2==1){//如果是奇数
cout<<m-1<<endl;
}
else{
cout<<1<<endl;
}
}
else{
if(m==4&&k==1){//唯一性
cout<<2<<endl;
}
else{
cout<<0<<endl;
}
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin>>t;
while(t--){
solve();
}
return 0;
}
以上,求过