1015 Reversible Primes (20)
題目描述:
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 (< 10^5^) and D (1 < D <= 10), you are supposed to tell if N is a reversible prime with radix D.
輸入格式:
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.輸出格式:
For each test case, print in one line “Yes” if N is a reversible prime with radix D, or “No” if not.
解題方法:
可能有很多人在一開始就沒讀懂題目,這裏稍微解釋一下。每行輸入的第一個數是10進制下的數,第二個輸入的數表示相應的進制。也就是說,對23 2這個案例,首先求23得二進制碼:10111,那麼反轉後的二進制碼:11101。然後再把11101轉爲10進制:29,由此可見兩個數字都是素數,所以輸出yes。
因此這題只需要判斷素數,轉換進制即可完成。對於化爲D進制數,可以使用除D取餘法,比如5
6 % 2 = 0, 然後 6 / 2 = 3
3 % 2 = 1, 然後 3 / 2 = 1
1 % 2 = 1, 然後 1 / 2 = 0 結束
得出011, (這個結果已經是反轉後的2進制碼)
易錯點:
1. 對素數的判斷1和2要單獨判斷
程序:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* 當然這裏轉換也不是一定要用到char類型數組接收,int也是可以的。不過這樣寫,可以稍稍減少一點內存,因爲char是1個字節的,而int是2個字節的*/
int reverse(int x, int D)
{ /* 反轉在該進制下的反轉D進制碼並計算在十進制下的結果 */
char num[16];
int idx = 0, sum = 0, expon = 0;
while (x)
{ /* 除D取餘法(不理解的可以隨便對一個數手算幫助理解) */
num[idx++] = x % D + '0';
x /= D;
}
for (int i = idx-1; i >= 0; i--) /* 上面結果已經是反轉了 */
sum += (num[i]-'0') * pow(D, expon++);
return sum;
}
bool isPrime(int x)
{ /* 判斷x是否爲素數 */
if (x == 2) /* 2是素數 */
return true;
if (x == 1) /* 1不是素數 */
return false;
for (int i = 2; i <= sqrt(x); i++)
if (x % i == 0)
return false;
return true;
}
int main(int argc, char const *argv[])
{
int N, D;
while (scanf("%d", &N))
{
if (N < 0)
break;
scanf("%d", &D);
if (isPrime(N) && isPrime(reverse(N, D)))
printf("Yes\n");
else
printf("No\n");
}
return 0;
}
如果對您有幫助,幫忙點個小拇指唄~