A1015. Reversible Primes
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
1 #include<cstdio> 2 #include<iostream> 3 #include<algorithm> 4 #include<math.h> 5 using namespace std; 6 int numReverse(int N, int radix){ 7 int num[50], temp, index = 0, ans = 0; 8 do{ 9 temp = N % radix; 10 num[index++] = temp; 11 N = N / radix; 12 }while(N != 0); 13 for(int i = index - 1, P = 1; i >= 0; i--){ 14 ans += num[i] * P; 15 P = P * radix; 16 } 17 return ans; 18 } 19 int isPrime(int N){ 20 int sqr = (int)sqrt(N * 1.0); 21 if(N == 1) 22 return 0; 23 for(int i = 2; i <= sqr; i++){ 24 if(N % i == 0) 25 return 0; 26 } 27 return 1; 28 } 29 int main(){ 30 int N, D, N2; 31 while(1){ 32 scanf("%d", &N); 33 if(N < 0) 34 break; 35 scanf("%d", &D); 36 int temp = numReverse(N, D); 37 if(isPrime(N) && isPrime(temp)) 38 printf("Yes\n"); 39 else printf("No\n"); 40 } 41 cin >> N; 42 return 0; 43 }
总结:
1、判断素数:
int isPrime(int N){ int sqr = (int)sqrt(N * 1.0); //N应该转换为小数 if(N == 1) //当N = 1时应返回false,容易忽略,1不是素数 return 0; for(int i = 2; i <= sqr; i++){ //i <= sqr; i从2开始查找 if(N % i == 0) return 0; } return 1; }