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


    题目很简单,只需要先把数字用除k取余法转化为相应的进制,然后正着和反着分别转化为十进制再判断是否为素数,需要注意的是1不是素数。

    另外为了避免使用power函数,从低位开始运算,让基数每次自乘。

    除k取余法的过程为:



    代码如下:

    #include <iostream>
    #include <stdlib.h>
    #include <stdio.h>
    #include <math.h>
    #include <vector>
    
    using namespace std;
    
    bool isPrime(int input){
    
        if(input == 1) return false;
        for(int i = input - 1;i > 1; i--){
            if((input % i)==0){
                return false;
            }
        }
        return true;
    
    }
    
    int decValueWithVector(vector<int> num, int radix, bool isReverse){
        int result = 0;
        int m = 1;
        if(isReverse == true){
    
            for(int i = num.size() - 1; i >=0; i--){
                result += m*num[i];
                m*=radix;
            }
    
        }else{
    
            for(int i = 0; i < num.size(); i++){
                result += m*num[i];
                m*=radix;
            }
    
        }
    
        return result;
    
    }
    
    int main()
    {
        int N,D;
    
        vector<int> num_result(0);
    
        bool loop = true;
    
        while(loop){
    
            cin >> N;
            if(N < 0){
    
                break;
    
            }
    
            cin >> D;
            int shang,yu;
            int temp = N;
            while(temp != 0){
                shang = temp / D;
                yu = temp % D;
                temp = shang;
                num_result.push_back(yu);
            }
            if(isPrime(decValueWithVector(num_result,D,false))&&isPrime((decValueWithVector(num_result,D,true)))){
                cout << "Yes" << endl;
            }else{
                cout << "No" << endl;
            }
            num_result.resize(0);
    
        }
    
        return 0;
    }
    
    
    
    



  • 相关阅读:
    SQL 数据库备份
    压力测试工具WAS
    petshop4.0 详解之八(PetShop表示层设计
    类库生成的dll 添加 注释
    硬盘格式化后 数据全部找回
    petshop4.0 详解之七(PetShop表示层设计)
    JS 显示动态更新时间
    petshop4.0 详解之六(PetShop表示层设计)
    在linux环境下搭建嵌入式开发平台
    收录 Uboot 详解
  • 原文地址:https://www.cnblogs.com/aiwz/p/6154175.html
Copyright © 2020-2023  润新知