zoukankan      html  css  js  c++  java
  • PAT (Advanced Level) Practice 1015 Reversible Primes (20分) (进制转换+素数判断)

    1.题目

    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

    2.题目分析

    先看给出的第一个数是不是素数,不是就输出NO,是的话再将这个数按照后面的进制要求转换为相应进制下的数,将这个数reverse一下,再转为十进制看是不是素数,是的话就是yes

    3.代码

    #include<iostream>
    #include<string>
    #include<cstring>
    #include<algorithm>
    #include<cmath>
    using namespace std;
    bool isprime(int t)
    {
    	if (t == 0 || t == 1)return false;
    	for (int i = 2; i <= sqrt(t); i++)
    		if (t%i == 0)return false;
    	return true;
    }
    int changea(string a,int d)//其它进制转十进制
    {
    	int num = 0;
    	for (int i = 0; i < a.length(); i++)
    		num += (a[i] - '0')*pow(d, a.length() - i - 1);
    	return num;
    }
    string changeb(int num,int d )//十进制转其它进制
    {
    	string answer = "";
    	int out[110];
    	int s = 0;
    	while (num > 0)
    	{
    		out[s++] = num%d;
    		num /= d;
    	}
    	for (int i = s - 1; i >= 0; i--)
    		answer += out[i] + '0';
    	reverse(answer.begin(), answer.end());
    	return answer;
    }
    int main()
    {
    	string a, b;
    	while (1)
    	{
    		cin >> a;
    		if (stoi(a) < 0)return 0;
    		cin >> b;
    		if (!isprime(stoi(a))) { printf("No
    "); continue; }
    		if(!isprime(changea(changeb(stoi(a),stoi(b)),stoi(b)))) { printf("No
    "); continue; }
    		printf("Yes
    ");
    	}
    }
  • 相关阅读:
    iOS-延迟操作方法总结
    IOS开发调整UILabel的行间距
    day16 包和random模块 time模块 进度条
    day15 软件开发规范 日志输出和序列化反序列化
    day14 列表生成式 生成器表达式 模块
    day13 函数三元表达式,递归
    day11 装饰器
    day10作用域与闭包
    day9 函数的形参和实参
    day8 函数
  • 原文地址:https://www.cnblogs.com/Jason66661010/p/12788812.html
Copyright © 2011-2022 走看看