• 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;
    }
    
    
    
    



  • 相关阅读:
    js数组的常见操作( push、pop、unshift、shift、splice、concat、 join)的用法
    js json对象与字符串转换
    js回调函数(callback)
    Array数组 [] 遍历方法
    65.rem布局详解(一图流)
    关于内存泄漏
    JS精粹知识点和我的解释
    再谈布局2-Flex布局
    input和button不同高 和 rem
    正则表达式学习
  • 原文地址:https://www.cnblogs.com/aiwz/p/6154175.html
Copyright © 2020-2023  润新知