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


题目很简单,只需要先把数字用除k取余法转化为相应的进制,然后正着和反着分别转化为十进制再判断是否为素数,需要注意的是1不是素数。

另外为了避免使用power函数,从低位开始运算,让基数每次自乘。

除k取余法的过程为:

1015. Reversible Primes (20)_第1张图片


代码如下:

#include 
#include 
#include 
#include 
#include 

using namespace std;

bool isPrime(int input){

    if(input == 1) return false;
    for(int i = input - 1;i > 1; i--){
        if((input % i)==0){
            return false;
        }
    }
    return true;

}

int decValueWithVector(vector num, int radix, bool isReverse){
    int result = 0;
    int m = 1;
    if(isReverse == true){

        for(int i = num.size() - 1; i >=0; i--){
            result += m*num[i];
            m*=radix;
        }

    }else{

        for(int i = 0; i < num.size(); i++){
            result += m*num[i];
            m*=radix;
        }

    }

    return result;

}

int main()
{
    int N,D;

    vector num_result(0);

    bool loop = true;

    while(loop){

        cin >> N;
        if(N < 0){

            break;

        }

        cin >> D;
        int shang,yu;
        int temp = N;
        while(temp != 0){
            shang = temp / D;
            yu = temp % D;
            temp = shang;
            num_result.push_back(yu);
        }
        if(isPrime(decValueWithVector(num_result,D,false))&&isPrime((decValueWithVector(num_result,D,true)))){
            cout << "Yes" << endl;
        }else{
            cout << "No" << endl;
        }
        num_result.resize(0);

    }

    return 0;
}






转载于:https://www.cnblogs.com/aiwz/p/6154175.html

你可能感兴趣的:(1015. Reversible Primes (20))