当前位置: 代码迷 >> 综合 >> 1015 Reversible Primes (20 分)按给定进制翻转后转化为十进制判断是不是素数
  详细解决方案

1015 Reversible Primes (20 分)按给定进制翻转后转化为十进制判断是不是素数

热度:39   发布时间:2023-12-14 01:15:11.0

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 (<10^?5) 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

题意:按给定进制翻转后转化为十进制判断是不是素数
思路:将输入进来的数转化为给定进制存到数组中,然后再将数组遍历一遍求出转化成的十进制,判断其是不是素数。但是这道题只拿了14分,素数函数肯定没有问题的,和柳神的答案对比后也基本思路差不多。
14分代码:

#include<iostream>
#include<cstdio>
#include<stack> 
#include<queue>
#include<vector>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
#include<set>
#include<map>using namespace std;int a[100];bool isprim(int x) {
    if(x <= 1) {
    return false;} else {
    for(int i = 2;i * i <= x;i++) {
    if(x % i == 0) {
    return false;}}return true;}
}int main() {
    int n,d;int length;while(scanf("%d",&n) != EOF) {
    memset(a,0,sizeof(a));if(n <= 0) {
    break;}if(!isprim(n)) {
    printf("No\n");continue;}scanf("%d",&d);do {
    a[length++] = n % d;n = n / d;	} while(n != 0);int sum = 0;for(int i = 0;i < length;i++) {
    sum = sum * d + a[i];}if(isprim(sum)) {
    printf("Yes\n");} else {
    printf("No\n");}}return 0;
}

柳神代码:

#include <cstdio>
#include <cmath>
using namespace std;
bool isprime(int n) {
    if(n <= 1) return false;int sqr = int(sqrt(n * 1.0));for(int i = 2; i <= sqr; i++) {
    if(n % i == 0)return false;}return true;
}
int main() {
    int n, d;while(scanf("%d", &n) != EOF) {
    if(n < 0) break;scanf("%d", &d);if(isprime(n) == false) {
    printf("No\n");continue;}int len = 0, arr[100];do{
    arr[len++] = n % d;n = n / d;}while(n != 0);for(int i = 0; i < len; i++)n = n * d + arr[i];printf("%s", isprime(n) ? "Yes\n" : "No\n");}return 0;
}