GYM 100883 J.palprime(枚举)

253 篇文章 2 订阅

Description
给出一整数b,找到不小于b的最小数n使得n是素数且n的二进制表示是回文的
Input
多组用例,每组用例给出一个01串表示b的二进制表示,串长不超过21位,以文件尾结束输入
Output
对于每组用例,输出满足条件的n的二进制表示
Sample Input
10
100
110
1000
Sample Output
11
101
111
10001
Solution
简单题,很多做法,直接暴力枚举2^21+300内所有数判合法可以,也可以2^11按位前半段(后半段回文过来即可)然后判是否是素数,我用的是后一种方法
Code

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
#define INF 0x3f3f3f3f
#define maxn 5555
int a[33],b[maxn],res;
char s[33];
bool check(int m)
{
    for(int i=2;i*i<=m;i++)
        if(m%i==0)return 0;
    return 1;
}
void init()
{
    res=0;
    for(int n=2;n<=22;n++)
    {
        a[1]=a[n]=1;
        int N=1<<((n-1)/2);
        for(int i=0;i<N;i++)
        {
            for(int j=0;j<(n-1)/2;j++)
                if(i&(1<<j))a[j+2]=1;
                else a[j+2]=0;
            for(int j=n-1;j>n/2;j--)a[j]=a[n+1-j];
            int temp=0;
            for(int j=1;j<=n;j++)temp=2*temp+a[j];
            if(check(temp))b[res++]=temp;
        }
    }
    sort(b,b+res);
}
int main()
{
    init();
    while(~scanf("%s",s))
    {
        int temp=0,len=strlen(s);
        for(int i=0;i<len;i++)temp=2*temp+s[i]-'0';
        int pos=lower_bound(b,b+res,temp)-b;
        int n=b[pos],cnt=0;
        while(n)a[cnt++]=n%2,n/=2;  
        for(int i=cnt-1;i>=0;i--)printf("%d",a[i]);
        printf("\n");
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值