0%

PAT-1015 Reversible Primes

1015 Reversible Primes

题意

给定一个数以及它的进制数,判断数本身以及它的数位的逆是不是都是质数

思路

按照题目来判断原数是不是质数,数位逆转后再判断是不是质数

源码

line_number: true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include <stdio.h>
#include <map>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <unordered_map>
#include <algorithm>
#include <cmath>
using namespace std;

// 判断是不是质数
bool isPrime(int iNum)
{
if(iNum <= 1)
{
return false;
}
if(iNum == 2)
{
return true;
}

int iHalf = iNum / 2;
int iDivisorCount = 0;
for(int i = 2; i <= iHalf; i++)
{
if(iNum % i == 0)
{
return false;
}
}
return true;
}

// 数位反转
int reverse(int iNum, int iD)
{
int iReverse = 0;
while(iNum != 0)
{
iReverse = iReverse * iD + iNum % iD;
iNum = iNum / iD;
}
return iReverse;
}

int main()
{
int iN, iD;
while(cin>> iN)
{
if(iN < 0)
{
break;
}
cin>> iD;
if(isPrime(iN) == false)
{
cout<<"No"<<endl;
continue;
}
if(isPrime(reverse(iN, iD)) == false)
{
cout<< "No" <<endl;
}
else
{
cout<<"Yes"<<endl;
}
}

return 0;
}