当前位置:编程学习 > C/C++ >>

PAT-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
 
分析:给出一个数N和一个基数D。首先这个数必须是素数。其次,将这个数(1)转为D进制数(2)将这个D进制数反转(3)将反转后的数再转为十进制数,这个十进制数依然是素数。 这样我们就输出“Yes”。
题目不难,就是表述不清楚,看的费劲。
 
判断素数:一个数N,如果从2到sqrt(N)都不存在因子,则认为这个数是素数。 注意:0和1不是素数。
 
将十进制数转为n进制数:(待补充。。。)
 
 
 
#include<iostream>  
#include<string.h>  
#include<math.h>  
using namespace std;  
  
bool is_Prime(int a)  
{  
    int i;  
    if(a==0 || a==1) return false;  
  
    //注意是i<=sqrt(),之前弄成i<sqrt,一直出错  
    for(i=2; i <= sqrt((double)a); i++){  
        if( a%i == 0) return false;  
    }  
  
    return true;  
}  
  
int change(int n,int d){  
    int a[100000];  
    memset(a,0,sizeof(a));  
    int total = 0;  
    int j;  
    int i;  
    for(i=0; ; i++){  
        a[i] = n%d;  
        n /= d;  
        if(n==0) break;  
    }  
  
    for(j=0; j<=i; j++)  
    {  
        total = total*d + a[j];  
    }  
/*也可以这样写 
    do  
    { 
        total = total*d + n%d; 
        n/=d; 
    } while (n != 0); 
*/  
    return total;  
}  
  
int main()  
{  
    int N,D;  
    while(cin>>N){  
        if( N<0 ) break;  
        cin>>D;  
        if( is_Prime(N) && is_Prime( change(N,D) )){  
            cout<<"Yes"<<endl;  
        }  
        else{  
            cout<<"No"<<endl;  
        }  
    }  
    return 0;  
}  

 

 
补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,