1015. Reversible Primes (20)

简介: #include #include using namespace std;/* 要求:(1)判断该数是否为素数(2)判断该数基于d进制的逆序的十进制数是否为素数 思路:(1)IsPrime判断素数 (2)...


#include <iostream>
#include <cmath>
using namespace std;

/*
 要求:(1)判断该数是否为素数(2)判断该数基于d进制的逆序的十进制数是否为素数
 思路:(1)IsPrime判断素数  (2)基于d进制的逆序,并转换为十进制
 */

bool IsPrime(int n){
    if(n <= 1) return false;
    for (int i = 2; i <= sqrt(n); i++) {
        if(n % i == 0) return false;
    }
    return true;
}


int main(int argc, const char * argv[]) {
    int n, d;
    while (scanf("%d", &n) != EOF) {
        if (n < 0) {
            break;
        }
        scanf("%d", &d);
        if (!IsPrime(n)) {
            printf("No\n");
            continue;
        }
        
        //基于d进制的逆序(给出的数是十进制呀 所以要换成d进制后再逆序)
        int a[100], m = 0, len = 0;
        while (n) {
            a[len++] = n % d;
            n /= d;
        }
        for (int i = 0; i < len; i++) {
            m = m * d + a[i];
        }
        
        if (IsPrime(m)) {
            printf("Yes\n");
        }else{
            printf("No\n");
        }
    }
    
    return 0;
}


目录
相关文章
hdoj 4715 Difference Between Primes 素数筛选+二分查找
hdoj 4715 Difference Between Primes 素数筛选+二分查找
39 1
|
测试技术
LeetCode 204. Count Primes
统计所有小于非负整数 n 的质数的数量。
52 0
LeetCode 204. Count Primes
LeetCode之Sum of Two Integers
LeetCode之Sum of Two Integers
124 0
[LeetCode]--29. Divide Two Integers
Divide two integers without using multiplication, division and mod operator. If it is overflow, return MAX_INT. 以前我记得做过乘法变加法吧,这个有点像除法变减法,用位运算,二进制嘛,左移一位相当于乘以二。 一个有趣的是 Math.abs(-2147483648
1130 0
|
Java
[LeetCode]--371. Sum of Two Integers
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Example: Given a = 1 and b = 2, return 3. Credits: Special thanks to @fujiaozhu for addin
1156 0
[LeetCode] Sum of Two Integers
The code is as follows. public class Solution { public int getSum(int a, int b) { return b == 0 ? a : getSum(a ^ b, (a & b)
1123 0
LeetCode - 29. Divide Two Integers
29. Divide Two Integers Problem's Link  ---------------------------------------------------------------------------- Mean:  不使用乘法、除法、取模运算,实现两个数相除.
832 0