码迷,mamicode.com
首页 > 其他好文 > 详细

PAT1015:Reversible Primes

时间:2017-10-14 23:27:34      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:names   十进制   inpu   pie   代码   reverse   sam   ini   its   

1015. Reversible Primes (20)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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

思路

1.先判断十进制数N是否是素数,不是直接输出No。
2.如果N是素数先把N转为D进制数N1,然后得到的D进制数N1按颠倒的位数转换成十进制数N2,检查N2是否是素数即可。
例:
1)比如输入N = 23、D = 2,23是素数,那么23转2进制数为10111,颠倒后为11101,11101转换为十进制数后为29,29也是素数,输出Yes。
2)又比如N = 23,D = 6 , 23转6进制数为35,颠倒后为53,53转10进制数为33,33不是素数,输出No。

代码
#include<iostream>
#include<vector>
using namespace std;

bool isPrime(const int num)
{
    if(num != 2 && num % 2 == 0 || num == 1)
        return false;
    for(int i = 2;i * i <= num;i++)
    {
        if(num % i == 0)
            return false;
    }
    return true;
}

int main()
{
    int N;
    while(cin >> N)
    {
        if(N < 0)
            break;
        int D;
        cin >> D;
        if(!isPrime(N))
        {
            cout << "No" << endl;
            continue;
        }
        vector<int> digit(100,0);
        int index = 0;
        while( N != 0)
        {
            digit[index++] = N % D;
            N /= D;
        }
        for(int i = 0;i < index;i++)
        {
            N = N * D + digit[i];
        }
        if(isPrime(N))
            cout << "Yes" << endl;
        else
            cout << "No" << endl;
    }
}

 

PAT1015:Reversible Primes

标签:names   十进制   inpu   pie   代码   reverse   sam   ini   its   

原文地址:http://www.cnblogs.com/0kk470/p/7668863.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!