A1015 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 (<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

题意:

 给出正整数N和进制radix,如果N(<10​5​​)是素数,且N在radix(1<D≤10)进制下反转后的数在十进制下也是素数,则输出 Yes,否则输出 No。当输入的N为负数时,结束输入。

知识点:

  1. while...EOF 型:scanf函数的返回值为其成功读入参数的个数。对于正常控制台中的输入一般不会失败,只有在读取文件时,到达文件末尾导致无法读取现象,才会产生读入失败。这是,scanf函数会返回-1,而不是0,使用EOF(End of File)来表示 -1。即就是说,当题目没有说明有多少数据需要读入时,就可以利用scanf函数的返回值是否为EOF来判断输入是否结束。

思路:

进制转化类型题目常规实现参考:B1022 D进制的A+B

先判断N是否为素数,再转换进制,因为转换进制后数字变为存储于 int 型数组中是数(而且此时数字从低到高为反序),因此直接计算该数对应的十进制数,再此判断是否为素数,如全部满足,输出Yes即可。

#include <cstdio>
#include <cmath>
bool isPrime(int n){
  if(n <= 1)
    return false;
  int sqr = (int)sqrt(1.0 * n);
  for(int i = 2; i <= sqr; i++){
    if(n % i == 0)
      return false;
  }
  return true;
}
int d[111];
int main(){
  int n, radix;
  while(scanf("%d", &n) != EOF){
    if(n < 0)
      break;
    scanf("%d", &radix);
    if(isPrime(n) == false)
      printf("No\n");
    else{
      int len = 0;
      do{
        d[len++] = n % radix;
        n /= radix;
      }while(n != 0);   //此时数字从低到高为逆序
      for(int i = 0; i < len; i++){   //逆序转化为十进制
        n = n * radix + d[i];
      }
      if(isPrime(n) == true)
        printf("Yes\n");
      else
        printf("No\n");
    }
  }
  return 0;
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值