题目
如果一个数本身是素数,而且在d进制下反转后的数在十进制下也是素数,就输出Yes,否则就输出No
十分想吐槽一下这个原本的英文题目,我看了半天没看懂2333、
当然这也不排除是我zz.....
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
分析
1.判断素数,用了一般的线性筛法。但是一不小心给自己挖了个坑。
有可能出现数字1 ,但是觉得radix 不可能是1 ,就放过去了???(radix是几和原来的数字并没有什么关系。。)
isprime[1] = 1这句必须要加上。
2.进制转换,建议记住这个套路,不要自己老用什么stack
int idx = 0;
ll ans = 0;
do
{
revN[idx ++] = num % radix;
num = num / radix;
}while(num != 0);
这个是反着存的。
代码
#include<iostream>
#include<algorithm>
#include<sstream>
#include<queue>
#include<cmath>
#include<string.h>
#include<map>
#include<stack>
using namespace std;
typedef long long ll;
const ll maxn = 1000005;
int N ;
int revN[200];
int radix;
int isprime[maxn];
void judge()
{
memset(isprime , 1 , sizeof(isprime));
isprime[2] = 1;
isprime[0] = 0;
isprime[1] = 0;//这里有个测试点。。。。
for(ll i = 2; i < maxn ; i++)
{
if(isprime[i] == 0) continue;
for(ll j = i * i ; j < maxn ; j += i)
{
isprime[j] = 0;
}
}
}
ll str2rev(ll num)
{
int idx = 0;
ll ans = 0;
do
{
revN[idx ++] = num % radix;
num = num / radix;
}while(num != 0);
for(int i = 0 ; i < idx ; i ++)
{
ans = ans * radix ;
ans += revN[i];
}
return ans;
}
int main()
{
judge();
while(scanf("%d" , &N) != EOF)
{
if( N < 0) return 0;
cin >> radix;
if( ! isprime[N])
{
cout << "No" << endl;
continue;
}
ll n = str2rev(N);
printf("%s", isprime[n]? "Yes\n" : "No\n");
}
}