1015. Reversible Primes (20)
时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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 -2Sample Output:
Yes Yes No
做麻烦了,从输入的a中取出最后一位可以直接拿过来当反转的第一位来用,以此类推,没有必要再生成字符串。
import java.util.*;
public class Main {
public static boolean IsPrime(int a) {
if(a==1)
return false;
else if(a==2)
return true;
else {
for(int i=2;i*i<=a;i++) {
if(a%i==0)
return false;
}
return true;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
int a=in.nextInt();
while(a>0) {
int radix=in.nextInt();
String as=new String("");
String ass=new String("");
int num=0;
int aa=a;
while(a>0) {
char ch;
int dig=a%radix;
ch=(char)('0'+dig);
as=ch+as;
a/=radix;
}
int len=as.length();
for(int i=len-1;i>-1;i--) {
char ch=as.charAt(i);
ass=ass+ch;
}
for(int i=0;i<len;i++) {
char ch=ass.charAt(i);
num=num*radix+(int)(ch-'0');
}
if(IsPrime(num)&&IsPrime(aa))
System.out.println("Yes");
else
System.out.println("No");
a=in.nextInt();
}
}
}