• 浙大pat甲级题目---Reversible Primes (20)


    先贴题目:

    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

    题解:本题意思是判断一个数和该数在规定进制条件下反转后是否为素数。题目本身比较简单,但是一定要理解题意(我一开始就理解错题意)
    关键是求该数在规定进制反转后在转为十进制后的数是否为素数。举个例子:
    23 2 这组答案,23在10进制下是个素数,转化为二进制为10111.反转后为11101,再转为10进制为39,也是个质数。所以输出Yes
    题目思路:
    首先需要判断某个数是否为素数的函数(注意二为素数)
    其次将这个数按照位数反转即可。
    代码如下:
     1 #include <iostream>
     2 #include<math.h>
     3 using namespace std;
     4 int convert(int n,int r);
     5 int convert_todicimal(int n,int r);
     6 bool judge(int n)
     7 {
     8     int i;
     9     if(n<=1)
    10         return false;
    11     if(n==2||n==3)
    12         return true;
    13     for(i=2;i<=sqrt(n)+1;i++)
    14     {
    15         if(n%i==0)
    16         {
    17             return false;
    18         }
    19     }
    20     return true;
    21 }
    22 int reverse(int n,int r)//十进制数倒置
    23 {
    24     int result=0;
    25     int temp=0;
    26     while(n!=0)
    27     {
    28         int t=n%r;
    29         result=(result*r)+t;
    30         n=n/r;
    31     }
    32     return result;
    33 }
    34 
    35 int main() {
    36     int n,r;
    37     while(1)
    38     {
    39         scanf("%d%d",&n,&r);
    40         if(n<0)
    41             break;
    42         //printf("%d
    ",convert(n,r));
    43         //printf("%d
    ",reverse(n,r));
    44         if(judge(n)&&judge(reverse(n,r)))
    45         {
    46             printf("Yes
    ");
    47         }
    48         else
    49         {
    50             printf("No
    ");
    51         }
    52     }
    53     return 0;
    54 }
  • 相关阅读:
    市值
    01-HTML基础与进阶-day3-录像237
    01-HTML基础与进阶-day3-录像236
    01-HTML基础与进阶-day3-录像235
    01-HTML基础与进阶-day2-HTML第二讲
    01-HTML基础与进阶-day2-HTML第一讲
    01H5-fe-html5-006插入视频
    MySQL 备份和恢复数据
    MySQL 索引
    MySQL 视图
  • 原文地址:https://www.cnblogs.com/SK1997/p/8511335.html
Copyright © 2020-2023  润新知