[USACO1.5]回文质数 Prime Palindromes
題目描述
因為151既是一個質(zhì)數(shù)又是一個回文數(shù)(從左到右和從右到左是看一樣的),所以 151 是回文質(zhì)數(shù)。
寫一個程序來找出范圍[a,b](5 <= a < b <= 100,000,000)( 一億)間的所有回文質(zhì)數(shù);
輸入輸出格式
輸入格式:
第 1 行: 二個整數(shù) a 和 b .
輸出格式:
輸出一個回文質(zhì)數(shù)的列表,一行一個。
輸入輸出樣例
輸入樣例#1:
5 500
輸出樣例#1:
5
7
11
101
131
151
181
191
313
353
373
383
說明
Hint 1: Generate the palindromes and see if they are prime.
提示 1: 找出所有的回文數(shù)再判斷它們是不是質(zhì)數(shù)(素數(shù)).
Hint 2: Generate palindromes by combining digits properly. You might need more than one of the loops like below.
提示 2: 要產(chǎn)生正確的回文數(shù),你可能需要幾個像下面這樣的循環(huán)。
題目翻譯來自NOCOW。
USACO Training Section 1.5
#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<cstring> #include<sstream> #include <algorithm> using namespace std; const int maxn=9989999; //小小的cheat 打表看到最大是9989899 bool isprime[maxn]; void prime(int o); bool hw(string tem); int main() {int a,b;cin>>a>>b;if(b>maxn) b=maxn-1;prime(b);for(int i=a;i<=b;i++){if(isprime[i]) {stringstream ob;ob<<i;string y;ob>>y;if(hw(y))printf("%d\n",i);}} } bool hw(string tem) {string w=tem;reverse(w.begin(),w.end());return (w==tem); } void prime(int w){for(int i=0;i<=w;i++) isprime[i]=true;//先全部置為真isprime[0]=isprime[1]=false;//1 0 不是素數(shù)for(int i=2;i<=w;i++){//從2開始往后篩if(isprime[i]){for(int j=2*i;j<=w;j+=i){isprime[j]=false;}}} }總結(jié)
以上是生活随笔為你收集整理的[USACO1.5]回文质数 Prime Palindromes的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大富翁游戏怎么玩
- 下一篇: POJ 2230 Watchcow 欧拉