1015 Reversible Primes (20)(20 分)
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 (< 10^5^) 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
分析
每行输入一个数N,基数D
若数N和它基于基数D的倒叙数都是质数,输出Yes,否则输出No。输入负数结束程序。
问题
1.质数的定义有点忘了,一开始把1也算成质数,有个测试点就不能通过。
质数定义为在大于1的自然数中,除了1和它本身以外不再有其他因数。
2.如何求倒叙数的问题。这个算法要记一下。
以10进制为例,n%10得到个位数,存到m,n右移一位。每次m前移一位加上得到的个位数。
代码
#include<stdio.h>
#include<iostream>
#include <stdlib.h>
#include <string>
#include<iomanip>
using namespace std;
int isPrime(int n){//判断是否是质数
int x,i;
if(n == 1) return 0;
if(n<=3) return 1;
for(i = 2;i<=n-1;i++){
if(n%i==0) return 0;
}
return 1;
}
int getni(int n,int d){
int m = 0;
while(n!=0) {
m=m*d+n%d;
n=n/d;
}
return m;
}
int main(){
int n,d;
while(scanf("%d",&n)!=EOF){
if(n<0) break;
else{
cin>>d;
//cout<<endl;
if(isPrime(n)==1&&isPrime(getni(n,d))==1) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
}
return 0;
}