D 原神数
题目分析
很明显我们可以枚举十进制位的排列来组成数,然后对于每个数字判断素数。
对于判素数可以采用 Miller-Rabin。
我们采用几个剪枝:
-
对于
0 到9 全部组一遍的数,一定都是3 的倍数(十进制位综合为45 ),所以不用考虑,这样可以剪掉3628800 个需要筛选的数。 -
缩小 Miller-Rabin 的模数数量(缩小到
2 个基本可以)。 -
可以在 Miller-Rabin 之前先把前
25 个质数的倍数筛了,这样又可以筛掉很多数,为程序加速。 -
手写全排列。
对于询问,我们把这些数预处理出来,每次二分左右边界即可。
代码
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define ld long double
ll qmul(ll a,ll b,ll mod)//快速乘
{
ll c=(ld)a/mod*b;
ll res=(ull)a*b-(ull)c*mod;
return (res+mod)%mod;
}
ll qpow(ll a,ll n,ll mod)//快速幂
{
ll res=1;
while(n)
{
if(n&1) res=qmul(res,a,mod);
a=qmul(a,a,mod);
n>>=1;
}
return res;
}
bool MRtest(ll n)//Miller Rabin Test
{
if(n<3||n%2==0) return n==2;//特判
ll u=n-1,t=0;
while(u%2==0) u/=2,++t;
ll ud[]={28178,9780504};
for(ll i=0;i<=1;i++)
{
ll a=ud[i];
ll v=qpow(a,u,n);
if(v==1||v==n-1||v==0) continue;
for(int j=1;j<=t;j++)
{
v=qmul(v,v,n);
if(v==n-1&&j!=t){v=1;break;}//出现一个n-1,后面都是1,直接跳出
if(v==1) return 0;//这里代表前面没有出现n-1这个解,二次检验失败
}
if(v!=1) return 0;//Fermat检验
}
return 1;
}
ll pr[31]={2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107};
bool is_prime(ll x)
{
for(ll i=0;i<=25&&pr[i]*pr[i]<=x;i++)
if(x%pr[i]==0) return false;
if(!MRtest(x)) return false;
return true;
}
bool vis[10];
ll l,r;
vector<ll> v;
void dfs(int c,ll s,int m)
{
if(c>m)
{
if(is_prime(s)) v.push_back(s);
return;
}
for(int i=0;i<=9;i++)
if(!vis[i])
{
if(i==0&&c==1) continue;
vis[i]=true;
dfs(c+1,s*10+i,m);
vis[i]=false;
}
}
ll read()
{
ll x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9') ch=getchar();
while(ch>='0'&&ch<='9')
x=x*10+ch-'0',ch=getchar();
return x*f;
}
int main()
{
for(int i=1;i<=9;i++) dfs(1,0,i);
int q;
cin>>q;
while(q--)
{
ll l,r;
l=read(),r=read();
int itl=lower_bound(v.begin(),v.end(),l)-v.begin();
int itr=upper_bound(v.begin(),v.end(),r)-v.begin()-1;
cout<<itr-itl+1<<"\n";
}
}
https://www.luogu.com.cn/record/156839141