PAT(甲) 1015 Reversible Primes (20)(详解)

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 (< 10^5^) and D (1 < D <= 10), you are supposed to tell if N is a reversible prime with radix D.


  • 输入格式
    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.

  • 输出格式
    For each test case, print in one line “Yes” if N is a reversible prime with radix D, or “No” if not.


解题方法:
可能有很多人在一开始就没读懂题目,这里稍微解释一下。每行输入的第一个数是10进制下的数,第二个输入的数表示相应的进制。也就是说,对23 2这个案例,首先求23得二进制码:10111,那么反转后的二进制码:11101。然后再把11101转为10进制:29,由此可见两个数字都是素数,所以输出yes。
因此这题只需要判断素数,转换进制即可完成。对于化为D进制数,可以使用除D取余法,比如5
6 % 2 = 0, 然后 6 / 2 = 3
3 % 2 = 1, 然后 3 / 2 = 1
1 % 2 = 1, 然后 1 / 2 = 0 结束
得出011, (这个结果已经是反转后的2进制码)


易错点:
1. 对素数的判断1和2要单独判断


程序:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

/* 当然这里转换也不是一定要用到char类型数组接收,int也是可以的。不过这样写,可以稍稍减少一点内存,因为char是1个字节的,而int是2个字节的*/
int reverse(int x, int D)
{   /* 反转在该进制下的反转D进制码并计算在十进制下的结果 */
    char num[16];
    int idx = 0, sum = 0, expon = 0;
    while (x)   
    {   /* 除D取余法(不理解的可以随便对一个数手算帮助理解) */
        num[idx++] = x % D + '0';
        x /= D;
    }
    for (int i = idx-1; i >= 0; i--)    /* 上面结果已经是反转了 */
        sum += (num[i]-'0') * pow(D, expon++);
    return sum;
}

bool isPrime(int x)
{   /* 判断x是否为素数 */
    if (x == 2) /* 2是素数 */ 
        return true;
    if (x == 1) /* 1不是素数 */
        return false;
    for (int i = 2; i <= sqrt(x); i++)
        if (x % i == 0)
            return false;
    return true;
}

int main(int argc, char const *argv[])
{
    int N, D;
    while (scanf("%d", &N))
    {
        if (N < 0)
            break;
        scanf("%d", &D);
        if (isPrime(N) && isPrime(reverse(N, D)))
            printf("Yes\n");
        else
            printf("No\n");
    }

    return 0;
}

如果对您有帮助,帮忙点个小拇指呗~

猜你喜欢

转载自blog.csdn.net/invokar/article/details/80545139
今日推荐