zoukankan      html  css  js  c++  java
  • 洛谷 P1217 [USACO1.5]回文质数 Prime Palindromes(埃氏筛法)

    题目链接:

    P1217 [USACO1.5]回文质数 Prime Palindromes

    思路:

    1.首先我们需要知道偶数长度的回文不会是素数,因为它必定能被11整除,这样我们就能将范围缩到一千万以内;
    2.然后用埃氏筛法,得到一千万以内的所有素数,再挨个判断他们是否为回文即可;

    代码:

    #include<bits/stdc++.h>
    using namespace std;
    const int maxn=1e7;
    vector<int> prime;
    bool isPrime[maxn]; 
    void sieve(int n){   //[2,n)
    	for(int i=2;i<n;++i) isPrime[i]=true;
    	for(int i=2;i<n;++i){
    		if(isPrime[i]){
    			prime.push_back(i);
    			for(int j=(i<<1);j<=n;j+=i) isPrime[j]=false;
    		}
    	}
    }
    int a,b;
    char c[10];
    void init_(){
    	sieve(maxn);
    	for(int i=0;i<=9;++i) c[i]=i+'0';
    }
    bool isPal(int n){
    	string x="",y;
    	while(n) x+=c[n%10],n/=10;
    	y=x; reverse(y.begin(),y.end());
    	return x==y;
    }
    int main(){
    	init_();
    	scanf("%d %d",&a,&b);
    	for(int& x:prime){
    		if(x>b) break;
    		if(x>=a&&isPal(x)) cout<<x<<'
    ';
    	}
    	return 0;
    }
    
  • 相关阅读:
    黄宗禹9.11作业
    黄宗禹第一次作业
    9.11
    9.18
    计算平均速度
    圆的周长与面积
    JAVA 作业
    9.11
    9.25
    计算平均速度题
  • 原文地址:https://www.cnblogs.com/yuhan-blog/p/12308705.html
Copyright © 2011-2022 走看看