PAT (Advanced Level) Practice 1015 Reversible Primes
题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805495863296000
给定基数D的情况下,判断一个数是否为素数并在此基数下反转后仍然是素数。将这个数在给定基数下转换成十进制数,即可直接判断
代码如下:
#include <iostream> #include <stack> #include <math.h> #include <stdio.h> using namespace std; int ReverseNumber(int n, int d){ //将数转换成D基数下的十进制数 int sum = 0; do{ sum = sum*d + n%d; n /= d; } while(n != 0); return sum; } bool IsPrime(int n){ //判断素数 if(n == 0 || n == 1 ) return false; for(int i = 2; i <= sqrt((double)n); i++){ if(n%i == 0) return false; } return true; } int main() { int n,d; while(scanf("%d",&n) != EOF && n >= 0){ scanf("%d",&d); if(IsPrime(n) && IsPrime(ReverseNumber(n,d))) printf("Yes\n"); else printf("No\n"); } return 0; }