PRIMPERM - Prime Permutations

将题目分解成两个部分:

  • 判断素数

如果用暴力筛因子的方法,在 $t \le 10^4,n \le 10^7$ 下肯定是要超时的,所以用了时间和空间都比较廉价的埃氏筛法。

代码:

bool f[10000010];//值为1不是质数。
void init(){
    f[0]=f[1]=1;//0,1不是质数。
    for(int i=2;i<=10000000;i++){
        if(!f[i]){
            for(int j=2*i;j<=10000000;j+=i){
                f[j]=1;//质数的倍数不是质数。
            }
        }
    }
}
  • 全排列

手写全排列太麻烦了,所以这里用函数 next_permutation,用法:next_permutaion(数组名+起始地址,数组名+末尾地址+1),注意使用之前要对数组进行升序排序。


代码(前面都讲清楚了,不放注释):

#include<bits/stdc++.h>
using namespace std;
int w[11],prime[10000010];
bool f[10000010];
void init(){
    f[0]=f[1]=1;
    for(int i=2;i<=10000000;i++){
        if(!f[i]){
            for(int j=2*i;j<=10000000;j+=i){
                f[j]=1;
            }
        }
    }
}
int main(){
    ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    init();
    int T;
    cin>>T;
    while(T--){
        int n,m=0,ans=0;
        cin>>n;
        while(n!=0){
            w[++m]=n%10;
            n/=10;
        }
        sort(w+1,w+1+m);
        do{
            if(!w[1]) continue;
            n=0;
            for(int i=1;i<=m;i++){
                n=n*10+w[i];
            }
            ans+=!f[n];
        }while(next_permutation(w+1,w+m+1));
        cout<<ans<<endl;
    }
    return 0;
}
posted @ 2023-05-02 13:31  shoot_down  阅读(15)  评论(0)    收藏  举报  来源