您的位置:首页 > 其它

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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: