PAT1015
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.
比如在小数系统中73是一个反素数,因为37也是素数。
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.
现在给出任意两个正整数N和D,要求你写出N的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
判断N是不是素数,然后将N转换成D进制的数,然后翻转,然后转成10进制,然后判断结果和N是不是都是素数。
如23 2
转换成2进制是10111
反转是11101
转换成十进制是29
因为29和23都是素数,所以输出yes
#include<cstdio> #include<cstdlib> #include<iostream> #include<algorithm> using namespace std; //判读是不是素数,是返回1,不是返回0 int isSu(int number) { if(number < 2) return 0; for (int i = 2; i*i <= number; i++) { if(number%i == 0) return 0; } return 1; } //将一个整数转换成任意进制,,逆序之后转换成10进制返回 int change(int a,int d) { int result=0; int q=0; int jinzhi[60000]; while (a>0) { jinzhi[q] = a%d; a /= d; q++; } int dishu = 1; for (int i = q-1; i >= 0; i--) { result += jinzhi[i]*dishu; dishu*=d; } return result; } int main() { int n,d; while (true) { cin>>n; if(n<0) break; cin>>d; if(isSu(n) && isSu(change(n,d))) cout<<"Yes"<<endl; else cout<<"No"<<endl; } return 0; }
两点值得说明的,素数的判断没有用sqrt()而是用了i*i,还有就是我第一次错在,1不是素数上面了,其他都特别简单