PAT_A 1015. Reversible Primes (20)
2017-01-30 10:22
465 查看
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 (< 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
分析:反转素数是指一个素数反转后仍是一个素数。
CODE:
判断素数算法
反转
#include <iostream> #include<cmath> using namespace std; /* * reversible num base on radix d * test the two num which radix is 10 is prime*/ long reverse(long a,int b) { long c=0; long out=0; long count=0; do { count++; c*=10; c+=a%b; a/=b; }while(a>=1); //形成 radix:b形式的数c,方便检查错误 long tmp=0; //将c转化成十进制数,再进行判断素数 for(long i=0;i<count;i++) { tmp=c%10;//一开始写成了 c%b 最后两个测试点出错!细节呀! c/=10; out+=pow(b,i)*tmp; } return out; } //这个反转不错,上边的反转形成了中间数,这个更简洁 long reverse2(long n,int radix) { long num=n%radix; while((n/radix)!=0) { n/=radix; num = num*radix + n%radix; } return num; } //只判断前开方 bool isPrime1(int a) { int i; if(a==0 || a==1) return false; //注意是i<=sqrt(),之前弄成i<sqrt,一直出错 for(i=2; i <= sqrt((double)a); i++){ //写成 i*i<a也行 if( a%i == 0) return false; } return true; } //只判断前一半 bool isPrime(int a) { //别忘了1 、 2 if(a==1) return false; if(a==2) return true; for(int i=2;i<a/2+1;i++) { if(a%i==0) return false; } return true; } bool isPrime(int a,int b) { //自身及反转是否是素数 if(isPrime(a)==false) return false; else return isPrime(reverse(a,b)); } int main() { int data=10; int radix=10; while(true) { cin>>data; if(data<0) return 0; cin>>radix; if(isPrime(data,radix)==false) cout<<"No"<<endl; else cout<<"Yes"<<endl; } return 0; }
参考
浙江大学PAT上机题解析之1015. Reversible Primes (20)
【PAT】1015. Reversible Primes (20)
相关文章推荐
- Android 屏幕录制命令adb screenrecord
- Android 获取GPS速度
- Android 使用SVG动画
- SQL Server事务、隔离级别详解(二十九)
- 在ListView中增加HeaderView和FootView
- 关于Wampserver软件安装后输入localhost无法加载页面的原因
- 线性代数学习笔记(三)
- JavaScript中的深度克隆
- N26-第三周作业
- how to read openstack code: Neutron architecture
- SpringBoot缓存注解学习笔记之Redis
- PAT1063. 计算谱半径(20)
- Android编程之通知栏的用法小结
- 我的5.0护眼方案
- 年度热门开源项目
- Codeforces Round #256 (Div. 2)-C. Painting Fence
- java.sql.SQLException: ORA-00911: 无效字符 解决方法
- 4 网络、挂载、关机
- BFS-宽度优先搜索(Breadth First Search)—1
- 密码重置(南邮CTF)