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.java
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.app
Input Specification:ui
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.spa
Output Specification:code
For each test case, print in one line "Yes" if N is a reversible prime with radix D, or "No" if not.blog
73 10 23 2 23 10 -2
Yes Yes No
思路:先說一下題目的意思,判斷該十進制數N在D進制下的反轉再轉爲十進制是不是質數,好比sample中的23在二進制的反轉就是11101(原本是10111),再轉爲10進制就是29,是質數。ci
因此咱們要作的就是先把N轉爲D進製表示,反轉,再轉回十進制進行判斷。input
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 }