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
思路:先说一下题目的意思,判断该十进制数N在D进制下的反转再转为十进制是否是质数,比如sample中的23在二进制的反转就是11101(本来是10111),再转为10进制就是29,是质数。
所以我们要做的就是先把N转为D进制表示,反转,再转回十进制进行判断。
1 import java.math.BigInteger; 2 import java.util.*; 3 4 public class Main { 5 6 private static int revInRadixD(int num, int D) { 7 StringBuilder rev = new StringBuilder(); 8 int shang = num; 9 while (shang != 0) { 10 rev.append(shang % D); 11 shang /= D; 12 13 } 14 int result = 0; 15 int len = rev.length(); 16 for (int i = 0; i < len; i++) { 17 result += (rev.charAt(i) - '0') * Math.pow(D, len - 1 - i); 18 } 19 return result; 20 } 21 22 private static boolean isPrime(int num) { 23 if (num < 2) return false; 24 for (int i = 2; i <= Math.sqrt(num); i++) { 25 if (num % i == 0) { 26 return false; 27 } 28 } 29 return true; 30 } 31 32 public static void main(String[] args) { 33 Scanner in = new Scanner(System.in); 34 while (in.hasNext()) { 35 int N = in.nextInt(); 36 if (N < 0) return; 37 int D = in.nextInt(); 38 boolean isPrime = isPrime(N) && isPrime(revInRadixD(N, D)); 39 System.out.println(isPrime ? "Yes" : "No"); 40 } 41 42 } 43 }