PAT甲级-1015. Reversible Primes (20)

清疚 2022-05-30 05:45 255阅读 0赞

1015. Reversible Primes (20)

时间限制

400 ms

内存限制

65536 kB

代码长度限制

16000 B

判题程序

Standard

作者

CHEN, Yue

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

  1. 73 10
  2. 23 2
  3. 23 10
  4. -2

Sample Output:

  1. Yes
  2. Yes

No

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. #define INF 0x3f3f3f3f
  4. #define MAXN 1000010
  5. int a[MAXN];
  6. long long y=0;
  7. typedef long long ll;
  8. bool is_prime[MAXN];
  9. bool is_prime_small[MAXN];
  10. void segment_sieve()//素数打表
  11. {
  12. for(ll i=0; i*i<=MAXN; ++i)
  13. is_prime_small[i]=true;
  14. for(ll i=0; i<=MAXN; ++i)
  15. is_prime[i]=true;
  16. is_prime[0]=is_prime[1]=false;//0,1不是素数
  17. for(ll i=2; i*i<=MAXN; ++i)
  18. {
  19. if(is_prime_small[i])
  20. {
  21. for(ll j=2*i; j*j<=MAXN; j+=i)
  22. is_prime_small[j]=false;
  23. for(ll j=max(2LL,(i-1)/i)*i; j<=MAXN; j+=i)
  24. is_prime[j]=false;
  25. }
  26. }
  27. }
  28. void changeR(int x,int r)//逆置后转十进制判断是否素数
  29. {
  30. y=0;
  31. int cnt=0;
  32. while(x>0)
  33. {
  34. a[cnt++]=x%r;
  35. x/=r;
  36. }
  37. int temp=1;
  38. for(int i=cnt-1; i>=0; --i)
  39. {
  40. y+=(a[i]*temp);
  41. temp*=r;
  42. }
  43. //cout<<y<<endl;
  44. }
  45. int main()
  46. {
  47. segment_sieve();
  48. int x,r;
  49. while(cin>>x)
  50. {
  51. if(x<0) break;
  52. cin>>r;
  53. memset(a,0,sizeof(a));
  54. changeR(x,r);
  55. if(is_prime[x]&&is_prime[y]) cout<<"Yes"<<endl;
  56. else cout<<"No"<<endl;
  57. }
  58. return 0;
  59. }

发表评论

表情:
评论列表 (有 0 条评论,255人围观)

还没有评论,来说两句吧...

相关阅读