您的位置:首页 > 其它

1015. Reversible Primes (20)

2015-11-23 23:43 218 查看
A reversible prime in any number system is a prime whose "reverse" in that number system is also a prime. For example in the decimal system 73 is a reversible prime because its reverse 37 is also a prime.

Now given any two positive integers N (< 105) and D (1 < D <= 10), you are supposed to tell if N is a reversible prime with radix D.

Input Specification:

The input file consists of several test cases. Each case occupies a line which contains two integers N and D. The input is finished by a negative N.

Output Specification:

For each test case, print in one line "Yes" if N is a reversible prime with radix D, or "No" if not.
Sample Input:
73 10
23 2
23 10
-2

Sample Output:
Yes
Yes
No

-----------------华丽的分割线---------------
分析:可以先把<100001的所有素数找出来,然后对输入进行比对就好。找素数的过程中,采用了优化的方法,就是素数的整数倍(>=2)一定不是素数。
代码:
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<queue>

using namespace std;

#define Maxn 100001

bool isPrime[Maxn];

void FindAllPrime(void);
bool testPrime(int n);

int ConvertToDecimal(int n,int radix);

int main(void)
{
memset(isPrime,true,Maxn);
FindAllPrime();
int N,D;
while(scanf("%d",&N) && N >= 0)
{
scanf("%d",&D);
if(!isPrime
)
printf("No\n");
else
{
if(!isPrime[ConvertToDecimal(N,D)])
printf("No\n");
else
printf("Yes\n");
}
}
system("pause");
return 0;
}

void FindAllPrime(void)
{
int i;
int mid = sqrt(double(Maxn));
for(i=1;i<Maxn;++i)
{
if(!isPrime[i])
{
continue;
}
else
{
if(!testPrime(i))
{
isPrime[i] = false;
}
else
{
if(i<mid)
{
for(int k = i*i;k<Maxn;k=k+i)
{
isPrime[k] = false;
}
}
}
}
}
}

bool testPrime(int n)
{
if(n<=1)
return false;
else
{
int i;
double end;
end = sqrt(double(n)) + 1;
for(i=2;i<(int)end;++i)
{
if(n%i == 0)
return false;
}
return true;
}
}

int ConvertToDecimal(int n,int radix)
{
int result=0;
queue<int> temp;
do
{
temp.push(n%radix);
n /= radix;
}while(n!=0);

while(!temp.empty())
{
result = result * radix + temp.front();
temp.pop();
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: