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(<105)和D(1<D≤10),你应该判断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.
输入文件由几个测试用例组成。每种情况占用一行,该行包含两个整数N和D。输入以负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.
对于每个测试用例,如果N是以D为基数的可逆素数,则打印一行“是”;如果不是,则打印“否”。
Sample Input:
73 10
23 2
23 10
-2
Sample Output:
Yes
Yes
No
import java.util.Scanner;
class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true)
{
int n = sc.nextInt();
if(n < 0) break;
int r = sc.nextInt();
//如果本身就不是一个素数,就直接输出
if(!isprime(n))
{
System.out.println("No");
}
else
{
String N = "";
//将数字n转化成r进制下的字符串,此时字符串是数字n在r进制下的反转字符串
while(n != 0)
{
N += String.valueOf(n%r);
n /= r;
}
//将字符串转化为r进制下的整数
int value = translate(N,r);
if(isprime(value))
{
System.out.println("Yes");
}
else
{
System.out.println("No");
}
}
}
}
private static int translate(String n, int r) {
int sum = 0;
for(int i = n.length() - 1 ,unit = 1; i >= 0 ; i--,unit *= r)
{
sum += unit * (n.charAt(i) - '0');
}
return sum;
}
private static boolean isprime(int n) {
if(n < 2) return false;
for(int i = 2 ; i <= Math.sqrt(n) ;i++)
{
if(n % i == 0) return false;
}
return true;
}
}