PAT (Advanced Level) Practice 1015 Reversible Primes (20 分) 凌宸1642

题目描述:

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.

译: 一个可逆素数是:在某个数制中是一个素数,它在该数制中的“逆”也是一个素数。例如,在十进制中,73是可逆素数,因为它的逆37也是素数。现在给你任意两个正整数 N ( <10 5 ) 和 D (1< D ≤ 10) ,你应该说明 N是否是 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.

译:每个输入文件包含几个测试用例,每个用例包含两个正整数 ND占一行。以输入一个负数作为结束标志。


Output Specification (输出说明):

For each test case, print in one line Yes if N is a reversible prime with radix D, or No if not.

译:对于每个测试用例,在一行中输出,如果 ND 数制下的可逆素数输出 Yes 否则输出 No


Sample Input (样例输入):

73 10
23 2
23 10
-2

Sample Output (样例输出):

Yes
Yes
No

The Idea:

设计到素数,首先想到了先将题目范围内的所有素数标记出来,利用 筛法将所有素数对应的下标位置的数据值为 false。对于每个测试用例,在输入 N 后,判断 N 是否是一个素数,若不是素数可以直接输出 No ,如果 N 是一个素数,再将 N 转为 D 数制下的数字并取逆,再将其表示的数算 x出来,再判断 x 是否是一个素数,如果x是一个素数,则输出Yes,否则输出 No


The Codes:

#include<bits/stdc++.h>
using namespace std ;
#define MAX 100010
bool prime[MAX] = { false } ; // 初始化
void isPrime(){ // 筛选法求素数
for(int i = 2 ; i < MAX ; i ++ )
if(!prime[i])
for(int j = i + i ; j < MAX ; j += i)
prime[j] = true ; // i是素数,则 i 的所有倍数都不可能是素数
prime[1] = true ; // 注意 1 不是素数
}
int reverseNofD(int n , int d){
int m = 1 , eve[105] , cnt = 0 ;
for( ; n != 0 ; n /= d) eve[cnt ++] = n % d ;
for(int i = cnt - 1 ; i >= 0 ; m *= d , i --) // 逆置求加权值
n += m * eve[i];
return n ;
}
int main(){
isPrime() ; // 先标记素数
int n , d ;
while(scanf("%d" , &n) , n >= 0){
scanf("%d" , &d) ;
if(!prime[n]) // n 是素数
if(!prime[reverseNofD(n , d)]) printf("Yes\n") ; // 且 D 数制也是一个素数
else printf("No\n") ;
else printf("No\n") ;
}
return 0;
}

最新文章

  1. Ognl表达式基本原理和使用方法
  2. The hierarchy of the type is inconsistent错误问题
  3. Maven本地仓库及远程仓库
  4. MyISAM和InnoDB索引区别
  5. Hibernate的关联映射——单向1-1关联
  6. 数字字符与金钱RMB之间的转换
  7. OC基础(17)
  8. C puzzles详解【38-45题】
  9. PHP之implode与explode函数讲解
  10. Hadoop集群中Hbase的介绍、安装、使用
  11. HDU 3577 Fast Arrangement (线段树区间更新)
  12. DB操作用法总结。
  13. wxpython 32 位 ,python 64 位问题
  14. hdu 1536 SG函数模板题
  15. BeetleX和Asp.net Core之webapi基础性能对比
  16. 027_git添加多账号设置
  17. 2018年-2019年第二学期第六周C#学习个人总结
  18. Navicat软件安装
  19. SpringCloud学习(二)---Eureka
  20. [svc]arp协议的细枝末节

热门文章

  1. 微软收购 GitHub
  2. Python Tutorials
  3. website text select notes menu
  4. react-parent-child-lifecycle-order
  5. React &amp; redux-saga &amp; effects &amp; Generator function &amp; React Hooks
  6. 灰度发布 &amp; A/B 测试
  7. CentOS7安装ZooKeeper3.4.14
  8. Bitter.NotifyOpenPaltform : HTTP 异步消息接收调度中心&amp;mdash;开源贡献 之 一:简介
  9. python进阶(9)多线程
  10. mysql日志系统简单使用