洛谷題解 P1217 [USACO1.5]迴文質數 Prime Palindromes
阿新 • • 發佈:2018-12-13
[USACO1.5]迴文質數 Prime Palindromes
題目描述
因為151既是一個質數又是一個迴文數(從左到右和從右到左是看一樣的),所以 151 是迴文質數。
寫一個程式來找出範圍[a,b](5 <= a < b <= 100,000,000)( 一億)間的所有迴文質數;
輸入輸出格式
輸入格式:
第 1 行: 二個整數 a 和 b .
輸出格式:
輸出一個迴文質數的列表,一行一個。
輸入輸出樣例
輸入樣例#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: 找出所有的迴文數再判斷它們是不是質數(素數).
Hint 2: Generate palindromes by combining digits properly. You might need more than one of the loops like below.
提示 2: 要產生正確的迴文數,你可能需要幾個像下面這樣的迴圈。
題目翻譯來自NOCOW。
USACO Training Section 1.5
產生長度為5的迴文數:
for (d1 = 1; d1 <= 9; d1+=2) { // 只有奇數才會是素數
for (d2 = 0; d2 <= 9; d2++) {
for (d3 = 0; d3 <= 9; d3++) {
palindrome = 10000*d1 + 1000*d2 +100*d3 + 10*d2 + d1;//(處理迴文數...)
}
}
}
分割線————————————————————————————————————————————————————
我開始也想暴力來著,但是感覺不判斷迴文而是構造迴文更好
錯了好幾次才AC
構造迴文質數
這道題的核心思想是判斷迴文數和質數,方法道理都懂,就是:
記住要先構造前面再複製後面,
例如:迴文數2345432, 先構造234,再往後面加變成
2340432, 再在0的位置上上填0-9.
程式碼如下:
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int isPrime(int n)
{
int temp=n;
for(int i=2;i*i<=temp;i++)
{
if(n%i==0)
{
return 0;
}
}
return 1;
}
int shuw(int n)
{
return log10(n+0.5)+1;
}
int huiwen(int x)
{
int newed=0;
int n=x;
while(x)
{
newed=newed*10+x%10;
x/=10;
}
n=n*pow(10,shuw(n)+1)+newed;
return n;
}
int main()
{
int n,m,temp;
cin>>n>>m;
for(int i=n;i<=11;i++)
{
if(isPrime(i))
{
cout<<i<<endl;
}
}
for(int i=1;i<pow(10,shuw(m)/2);i++)
{
temp=huiwen(i);
for(int j=0;j<=9;j++)
{
int num=temp;
num+=j*pow(10,shuw(i));
if(num>=n&&num<=m)
{
if(isPrime(num))
{
cout<<num<<endl;
}
}
}
}
//cout<<pow(10,0);
//cout<<huiwen(4321);
return 0;
}